Been trying to remove the first element from a double pointer char array but i keep getting errors.
The input into the argv is from the keyboard using:
argv is defined in main as
int main(int argc, char **argv)
if(!fgets(*argv, 64, stdin))
return 0;
for (int i = 0; i < argc; i++)
{
j = 0;
while(j < strlen(*argv) - 1)
{
if(j == 0)
strcpy(argv + j, argv + j + 1);
j++;
}
}
Error:
warning: passing argument 2 of ‘strcpy’ from incompatible pointer type [-Wincompatible-pointer-types]
22 | { if(j == 0) strcpy(argv + j, argv + j + 1);
| ~~~~~~~~~^~~
| |
| char **
Your code has many compile issues, first you need to define variable j and also using correct braces as follow:
#include <string.h>
#include <stdio.h>
int main(int argc, char **argv) {
if(!fgets(*argv, 64, stdin))
return 0;
for (int i = 0; i < argc; i++)
{
int j = 0;
while(j < strlen(*argv) - 1)
{
if(j == 0)
strcpy(argv + j, argv + j + 1);
j++;
}
}
}
After that, I am strongly against using argv for reading a string because you don't know anything about its size in memory. Also, when you are using the strcpy you must pay attention to the sizes, the destination string should have at least the size of the source.
strlen only works on strings which means char * so using it on char ** is meaningless. The following code copies each string into the left item which I think very similar to what you want to do but please note that string size is very important and strcpy can cause issue.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
const int LEN = 255;
int main(int argc, char **argv) {
int n = 3;
// allocate memory for storing strings
char **strings = malloc(n * sizeof(char *));
// reading strings from user
// and store them
for (int i = 0; i < n; i++) {
strings[i] = malloc(LEN * sizeof(char));
// reads in at most one less than size characters from stream and stores them into the buffer pointed to by s
fgets(strings[i], LEN, stdin);
}
for (int i = 0; i < n - 1; i++) {
// here we consider all the strings has the max size as LEN
// so this copy does not cause error.
strcpy(strings[i], strings[i + 1]);
}
free(strings[n - 1]);
for (int i = 0; i < n - 1; i++) {
printf("[%d] %s", i, strings[i]);
}
}
Also, you can use the non-dynamic way as follows:
#include <string.h>
#include <stdio.h>
#define LEN 255
#define N 3
int main(int argc, char **argv) {
char strings[N][LEN];
// reading strings from user
// and store them
for (int i = 0; i < N; i++) {
// reads in at most one less than size characters from stream and stores them into the buffer pointed to by s
fgets(strings[i], LEN, stdin);
}
for (int i = 0; i < N - 1; i++) {
// here we consider all the strings has the max size as LEN
// so this copy does not cause error.
strcpy(strings[i], strings[i + 1]);
}
for (int i = 0; i < N - 1; i++) {
printf("[%d] %s", i, strings[i]);
}
}
Both programs have the following behavior:
Parham
Ali
Hassan
[0] Ali
[1] Hassan
Related
Just implementing a simple sorting algorithm to sort a string. I tried printing out the buff char array with printf("%s\n") but it came out blank. The contents of the array are there, though, and I checked with printing out each character of it. What am I missing here?
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
if (argc != 2)
{
printf("usage: ./sortstring string");
exit(1);
}
int size = 1; // 1 to account for '\0'
for (int i = 0; argv[1][i] != '\0'; i++)
{
size += 1;
}
char buff[size];
strcpy(buff, argv[1]);
char temp;
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (tolower(buff[i]) > tolower(buff[j]))
{
temp = buff[i];
buff[i] = buff[j];
buff[j] = temp;
}
}
}
// printf("%s\n", buff);
for (int i = 0; i < size; i++)
{
printf("%c", buff[i]);
}
return 0;
}
Change "%c" to "%d" in printf and see the result.
for (int i = 0; i < size; i++)
{
printf("%d", buff[i]);
}
strcpy copies terminating null byte with the source string.
You sorted terminating null byte with other characters.
Your sorting function is probably sorting the null character to position 0.
Instead of attempting to manually count characters in "argc[1]", you could just use the "strlen" function. So, instead of
int size = 1; // 1 to account for '\0'
for (int i = 0; argv[1][i] != '\0'; i++)
{
size += 1;
}
You could use
int size = strlen(argv[1]);
Regards.
The problem is that you're initializing size with 1. I know you did that because you need one more char to \0, but after that, either you need to loop through size - 1 or you can decrease the value of size before your for loops.
Another thing you can do is: initialize size with 0, and use size + 1 while creating your array.
I'm trying to write my own concatenate program. What I'm doing is getting two strings as input from argv, creating a third empty character array that holds the length of argv[1] + argv[2], and then use two for loops to insert the characters from each argv string into the third string.
My first for loop seems to be working fine buy my second for loop isn't doing anything. Any ideas?
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *string1 = argv[1];
char *string2 = argv[2];
int string1Len = strnlen(string1, 50);
int string2Len = strnlen(string2, 50);
char string3[string1Len + string2Len + 1];
for (int i = 0; i <= string1Len; i++)
{
string3[i] = string1[i];
}
for(int i = (string1Len + 1); i <= (string1Len + string2Len); i++)
{
string3[i] = string2[i];
}
string3[string1Len + string2Len + 1] = '\0';
printf("%s %d %d\n", string3, string1Len, string2Len);
return 0;
}
You can simplify (and optimize) it by using the memcpy function
int main(int argc, char **argv) {
if (argc < 3) return 1;
const char *string1 = argv[0];
const char *string2 = argv[1];
const size_t string1Len = strlen(string1);
const size_t string2Len = strlen(string2);
char *string3 = malloc((string1Len + string2Len + 1) * sizeof(*string3));
memcpy(string3, string1, string1Len * sizeof(*string1));
memcpy(string3 + string1Len, string2, (string2Len + 1) * sizeof(*string2));
printf("%s %zu %zu", string3, string1Len, string2Len);
free(string3);
return 0;
}
And as the others said, pay attention to the nul terminator
Your second for loop "did nothing" because the first one worked up to the \0 character and included it in string3, so it's better to set the condition that the for loop works up to that character
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *string1 = argv[1];
char *string2 = argv[2];
int string1Len = strlen(string1);
int string2Len = strlen(string2);
int i;
char string3[string1Len + string2Len +1];
for (i = 0; string1[i]!='\0'; i++)
{
string3[i] = string1[i];
}
string3[i]=' '; //with space
++i;
for(int j = 0; string2[j]!='\0'; j++)
{
string3[i] = string2[j];
i++;
}
string3[string1Len + string2Len + 1] = '\0';
printf("%s %d %d\n", string3, string1Len, string2Len);
return 0;
}
There are two main issues in your code. Your first for loop copies the nul terminator from string1; so, anything you then add to your string3 after that will simply be ignored by functions like printf, because they see that nul as marking the end of the string.
In your second for loop, you have the same problem and, more critically, the i index you use is not valid for string2, as you have added the length of string1 to it.
Also, note that arrays in C start at zero, so you shouldn't add the 1 to the position of the final nul terminator.
Here's the "quick fix" for your current code:
for (int i = 0; i < string1Len; i++) { // Use "<" in place of "<=" or we copy the null terminator
string3[i] = string1[i];
}
for (int i = 0; i < string2Len; i++) { // Start "i" at 0 for valid "string2" index ...
string3[i + string1Len] = string2[i]; // ... and add "string1Len" for the destination index
}
string3[string1Len + string2Len] = '\0'; // Arrays start at ZERO, so don't add 1 for "nul" terminator position
However, there are some other points and possible improvements. Note that the strnlen function returns a size_t type, so you would be better off using that for your indexes. Also, as you know that the i index at the end of the first loop will still be valid for the next character, you can re-use that in the second loop (so long as you have declared it outside the first loop), and you can use a second index for the source string.
Also, as pointed out by chqrlie, you really should check that you have sufficient source data in the argv array.
Here's a version of your program with those additional changes:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
if (argc < 3) {
// Error-handling code
return 1;
}
char* string1 = argv[1];
char* string2 = argv[2];
size_t string1Len = strnlen(string1, 50);
size_t string2Len = strnlen(string2, 50);
size_t i, j;
char string3[string1Len + string2Len + 1];
for (i = 0; i < string1Len; i++) {
string3[i] = string1[i];
}
for (j = 0; j < string2Len; j++, i++) {
string3[i] = string2[j];
}
string3[i] = '\0';
printf("%s %zu %zu\n", string3, string1Len, string2Len); // "%zu" for "size_t"
return 0;
}
The problem in your second loop is that i starts beyond the beginning of the second string. However, if all you are trying to do is to write you own custom (max 50 chars) concatenate program, all you need to do is to printf the arguments one after the other and printf can help limit:
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i) printf("%.50s", argv[i]);
printf("\n");
return 0;
}
There is no need to copy in memory to a VLA and print.
If you need to create a function that concatenates, you better use malloc - as you can't safely return a VLA: (note, the following example will not limit to 50 chars):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* concat(int argc, char* argv[]) {
size_t totalsize = 1;
for (int i = 0; i < argc; ++i) totalsize += strlen(argv[i]);
char* ret = malloc(totalsize);
if (!ret) exit(1);
if (!argc) *ret = 0;
char* dst = ret;
for (int i = 0; i < argc; ++i) {
char* src = argv[i];
while (*dst++ = *src++); /* Copy also the \0 */
--dst;
}
return ret;
}
int main(int argc, char *argv[])
{
char* str = concat(argc - 1, argv + 1); /* Skip the program name */
printf("%s\n", str);
free(str);
return 0;
}
Note that the above examples will concatenate any number of strings.
The index values in both loops are incorrect:
you should stop the first loop when i == string1Len, hence the test should be:
for (int i = 0; i < string1Len; i++)
you should use add string1Len to the index into the destination string so bytes from the second string are appended to those of the first string:
for (int i = 0; i < string2Len; i++) {
string3[string1Len + i] = string2[i];
}
the index for the null terminator is string1Len + string2Len, adding 1 is incorrect as indexing is zero based in C:
string3[string1Len + string2Len] = '\0';
you should test the actual number of arguments provided to the program to avoid undefined behavior if some are missing.
Here is a modified version:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "missing arguments\n");
return 1;
}
char *string1 = argv[1];
char *string2 = argv[2];
int string1Len = strnlen(string1, 50);
int string2Len = strnlen(string2, 50);
char string3[string1Len + string2Len + 1];
for (int i = 0; i < string1Len; i++) {
string3[i] = string1[i];
}
for (int i = 0; i < string2Len; i++) {
string3[string1Len + i] = string2[i];
}
string3[string1Len + string2Len] = '\0';
printf("%s %d %d\n", string3, string1Len, string2Len);
return 0;
}
I'm working on a program that takes command line arguments and splits them in half and then orders them in lexicographical order.
For example:
hello, world!
would turn into:
he
ld!
llo
wor
I have a main method that reads through the arguments, a function that splits the arguments, and finally a function that is supposed to order the halves in lexicographical order. I can't get this to run properly because of argument type errors in the lexicographicalSort method and an incompatible pointer type in the main method. I'm having issues to correct these syntax errors, how exactly would I correct them? Also, is there anything here that would cause logical errors? This is what I have so far:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int splitString(char arg[], int n)
{
int len = strlen(arg);
int len1 = len/2;
int len2 = len - len1; // Compensate for possible odd length
char *s1 = malloc(len1 + 1); // one for the null terminator
memcpy(s1, arg, len1);
s1[len1] = '\0';
char *s2 = malloc(len2 + 1); // one for the null terminator
memcpy(s2, arg + len1, len2);
s2[len2] = '\0';
printf("%s\n", s1);
printf("%s\n", s2);
free(s1);
free(s2);
return 0;
}
int lexicographicalSort(char *arg[], int n)
{
char temp[50];
for(int i = 0; i < n; ++i)
scanf("%s[^\n]",arg[i]);
for(int i = 0; i < n - 1; ++i)
for(int j = i + 1; j < n ; ++j)
{
if(strcmp(arg[i], arg[j]) > 0)
{
strcpy(temp, arg[i]);
strcpy(arg[i], arg[j]);
strcpy(arg[j], temp);
}
}
for(int i = 0; i < n; ++i)
{
puts(arg[i]);
}
return 0;
}
int main(int argc, char *argv[])
{
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
int j = 1;
int k = strlen(argv[i]);
splitString(argv[i], j);
lexicographicalSort(argv[i], j);
}
}
}
Basic scheme is simple. Make an array of tuples {start_pointer, length}. Do some programming on args to split the args. Fill in the array as appropriate. Make sorting with qsort, or any other sort of your choise.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
char *s = "hello, world! . hello.....";
char *pc;
int i, n, nargs;
struct pp{
char *p;
int l;
};
struct pp args[10], hargs[20];
struct pp *pargs;
int cmp(const void * v0, const void * v1) {
struct pp *pv0 = v0, *pv1 = v1;
return strncmp(pv0->p, pv1->p, pv0->l);
}
int main(void)
{
for(pc = s, i = 0; *pc; ++i){
sscanf(pc, "%*[^ ]%n", &n);
if(n > 0){
args[i].p = pc;
args[i].l = n;
}
for(pc += n, n = 0; isspace(*pc); ++pc);
}
for(nargs = i, i = 0; i < nargs; ++i)
printf("%d arg is: %.*s\n", i, args[i].l, args[i].p);
putchar('\n');
for(i = 0, pargs = hargs; i < nargs; ++i){
if(args[i].l == 1){
pargs->p = args[i].p;
pargs->l = 1;
pargs = pargs + 1;
}else {
pargs->p = args[i].p;
pargs->l = args[i].l / 2;
pargs = pargs + 1;
pargs->p = args[i].p + args[i].l / 2;
pargs->l = args[i].l - args[i].l / 2;
pargs = pargs + 1;
}
}
putchar('\n');
for(nargs = pargs - hargs, i = 0; i < nargs; ++i)
printf("%d arg is: %.*s\n", i, hargs[i].l, hargs[i].p);
qsort(hargs, nargs, sizeof(struct pp), cmp);
putchar('\n');
for(i = 0; i < nargs; ++i)
printf("%d arg is: %.*s\n", i, hargs[i].l, hargs[i].p);
return 0;
}
https://rextester.com/GSH22767
Upon splitting a C string, one needs one extra char to store extra null-terminator. There is one answer that bypasses this by storing the length. For completeness, this is closer to your original intention: allocating enough space to copy the programmes arguments. It probably works slower, but one is free to use the strings elsewhere in the programme.
#include <stdlib.h> /* malloc free EXIT qsort */
#include <stdio.h> /* fprintf */
#include <string.h> /* strlen memcpy */
#include <errno.h> /* errno */
static int strcompare(const void *a, const void *b) {
const char *a_str = *(const char *const*)a, *b_str = *(const char *const*)b;
return strcmp(a_str, b_str);
}
int main(int argc, char **argv) {
char *spacev = 0, **listv = 0;
size_t spacec = 0, listc = 0;
int is_done = 0;
do { /* "Try." */
int i;
char *sv;
size_t j;
/* This requires argc > 1. */
if(argc <= 1) { errno = EDOM; break; }
/* Allocate maximum space. */
for(i = 1; i < argc; i++) spacec += strlen(argv[i]) + 2;
if(!(spacev = malloc(spacec)) || !(listv = malloc(argc * 2))) break;
sv = spacev;
/* Copy and split the arguments. */
for(i = 1; i < argc; i++) {
const char *const word = argv[i];
const size_t word_len = strlen(word),
w0_len = word_len / 2, w1_len = word_len - w0_len;
if(w0_len) {
listv[listc++] = sv;
memcpy(sv, word, w0_len);
sv += w0_len;
*(sv++) = '\0';
}
if(w1_len) {
listv[listc++] = sv;
memcpy(sv, word + w0_len, w1_len);
sv += w1_len;
*(sv++) = '\0';
}
}
/* Sort. */
qsort(listv, listc, sizeof listv, &strcompare);
for(j = 0; j < listc; j++) printf("%s\n", listv[j]);
is_done = 1;
} while(0); if(!is_done) {
perror("split");
} {
free(spacev);
free(listv);
}
return is_done ? EXIT_SUCCESS : EXIT_FAILURE;
}
It is simpler than your original; instead of allocating each string individually, it counts the maximum number of chars needed (plus two for two null terminators) and allocates the block all at once (space.) The pointers to the new list also need allocating, the maximum is 2 * argc. Once you copy and modify the argument list, one has an actual array of strings that one can qsort.
The overall gist of the program is to accept a command-line argument and for each string to print out backwards with variable length.
For example:
$ ./reversecommand hello 102
dnammocesrever/. olleh 201
I am having difficulty in implementing the thought process into code (e.g. with hello below). Any thoughts?
argc[0] ./reversecommand
argc[1] hello
argc[1][0] h -> argc[1][4] o
argc[1][1] e -> argc[1][3] l
argc[1][2] l -> argc[1][2] l
argc[1][3] l -> argc[1][1] e
argc[1][4] o -> argc[1][0] h
argc[2] 102
argc[3] [null]
#include <stdio.h>
#include <string.h>
static void print_reversed(const char *str, size_t len)
{
const char *ptr = str + len;
while (ptr > str)
putchar(*--ptr);
}
int main(int argc, char **argv)
{
for (int i = 0; i < argc; i++)
{
if (i != 0)
putchar(' ');
print_reversed(argv[i], strlen(argv[i]));
}
putchar('\n');
return 0;
}
There's no need to modify the strings; simply print the characters out one at a time in reverse order.
The logic is fairly straightforward: For each string in argv, reverse it and then print it.
#include <stdio.h>
#include <string.h>
void swap_characters(char *s, char *t) {
char tmp = *s;
*s = *t;
*t = tmp;
}
void reverse_string(char *s, int length) {
for (int i = 0; i < length / 2; ++i)
swap_characters(s + i, s + length - 1 - i);
}
int main(int argc, char **argv) {
for (int i = 0; i < argc; ++i) {
reverse_string(argv[i], strlen(argv[i]));
printf("%s ", argv[i]);
}
printf("\n");
}
Try this code give File name as reverse and put command line argument:-
There are lots of ways to do string reversal, and it is worth spending some time looking into because it is a standard interview question.
a simple implementation for null-terminated strings in C looks like
char * reverse(char * string){
int i;
int len = strlen(string);
for (i = 0; i < len/2; i++){
char c = string[i];
string[i] = string[len - i - 1];
string[len - i - 1] = c;
}
return string;
}
This version does manipulate the string, so we'll make a copy of the string just in case.
Once you have string reversal, you will need to run reverse on each argument, and print it out.
NOTE: arguments in a standard console application like this start with the name of the program as it was typed by the user. So if the program is invoked as ./my-program arg1 arg2, argv[0] will be "./my-program", so we will skip argv[0]
Using this, all you have to do is call reverse on each argument. like so
int main(int argc, char ** argv){
int i;
char * copy;
for ( i = 1; i < argc; i++){ // skip argv[0]
copy = strdup(argv[i]); // copy the string;
copy = reverse(copy);
printf("argv[%d] = \"%s\"\n", i, copy);
free(copy); // clean up the copy
}
}
All together, you get
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * reverse(char * string){
int i;
int len = strlen(string);
for (i = 0; i < len/2; i++){
char c = string[i];
string[i] = string[len - i - 1];
string[len - i - 1] = c;
}
return string;
}
int main(int argc, char ** argv){
int i;
char * copy;
for ( i = 1; i < argc; i++){ // skip argv[0]
copy = strdup(argv[i]); // copy the string;
copy = reverse(copy);
printf("argv[%d] = \"%s\"\n", i, copy);
free(copy); // clean up the copy
}
}
I'm using a dynamic array of strings in C:
char** strings;
I initialize it:
int max = 10;
strings = malloc(sizeof(char*) * max);
And copy a couple of dummy strings:
char* str = "dummy";
for (int i = 0; i < max; i++) {
strings[i] = malloc(strlen(str) + 1);
strncpy(strings[i], str, strlen(str) + 1);
}
Yet when I try to print this:
for (int i = 0; i < max; i++)
printf("array = %s", strings[i])
I get this error from Splint:
Value strings[] used before definition
An rvalue is used that may not be initialized to a value on some execution
path. (Use -usedef to inhibit warning)
Checking for NULL like this will not help:
for (int i = 0; i < max; i++)
if (strings[i] != NULL)
printf("array = %s", strings[i])
since strings[i] is still used "before definition".
Any ideas on how to solve this?
Edit: Will try this with a linked list instead, I think.
Also, complete code listing:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char** strings;
int i;
int max = 10;
char* str = "hello";
// Dynamic array with size max
strings = malloc(sizeof(char*) * max);
// Abort if NULL
if (strings == NULL)
return (-1);
// Define strings
for (i = 0; i < max; i++)
{
strings[i] = malloc(strlen(str) + 1);
// Abort if NULL
if (strings[i] == NULL)
{
// Undetected memory leak here!
free(strings);
return (-1);
}
strncpy(strings[i], str, strlen(str) + 1);
}
// Print strings
for (i = 0; i < max; i++)
{
if (strings[i] != NULL)
printf("string[%d] = %s\n", i, strings[i]);
}
// Free strings
for (i = 0; i < max; i++)
{
if (strings[i] != NULL)
free(strings[i]);
}
free(strings);
return 0;
}
I do not have Splint on my machine, so i cannot test with it, just an another way to your task:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int i, len, max;
char* str = "hello";
len = strlen(str) + 1;
max = 10;
char strings[max][len];
for (i = 0; i < max; i++) {
strcpy(strings[i], str);
}
for (i = 0; i < max; i++) {
printf("string[%d] = %s\n", i, strings[i]);
}
return 0;
}
Avoid creating non-continuous memory it would be better approach if you allocate memory in single malloc call.
Memory can be freed in single free call instead of multiple free call
max_rows * sizeof(char) will allocate 2 * 1
((strlen(str) * N) + 1) will allocate memory for every N element.
Here is my approch
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
size_t max_rows = 2;
char* str = "dummpy";
char* vec_s = (char *) malloc( max_rows * sizeof(char) * ((strlen(str) * max_rows) + 1));
for (int i = 0; i < max_rows; i++){
strcpy((vec_s + i), str);
printf("vec_s[%d]=%s\n", i, (vec_s + i));
}
free(vec_s);
return 0;
}