-2

I want to write a .c program using only libraries stdlib.h, stdio.h, and string.h. The program takes as input from the command line two words when the C program is is called - like this:

.mycode WORD1 WORD2

where WORD1 and WORD2 are both series of characters without spaces, forming a single word.

I want to store these two words in 2 char arrays in my code.

I also have to return a message to the user if more or less than EXACTLY 2 words are passed when the code was called.

Here is what I am trying:

int main(int argc, char *argv[])
{       
        //return error if user does not provide exactly two arguments
        if(argc!=3)
        {
                printf("Wrong number of arguments. Please input: ./codename WORD1 WORD2");
                exit(1);
        }

        char word1[]=argv[1];
        char word2[]=argv[2];

I hoped that if i called the code: ./mycode hello goodbye

then, word1 will equal "hello" and word2 will equal "goodbye", but I get a compile error trying to do this: char word1[]=argv[1];

prince12
  • 11
  • 4

1 Answers1

1

argv is an array of pointers to the strings. The strings they point to are persistent for the duration of the program. So, you can safely pass the pointers around and us them. But you need to use them as poiters:

int main(int argc, char *argv[])
{       
    //return error if user does not provide exactly two arguments
    if(argc!=3)
    {
            printf("Wrong number of arguments. Please input: ./codename WORD1 WORD2");
            exit(1);
    }

    char *word1 = argv[1]; // word is a pointer to char
    char *word2 = argv[2];
    printf ("%s, %s\n", word1, word2);
 }

The above code did not copy the strings, but rather it did copy pointers to the strings. The string itself occupies a certain place in memory and stays there.

In many cases you might want to really copy a string to the new location. One of the issues in your case is that you have no idea what would be the length of the string be.

You can use a dynamic allocation or varlength arrays, as in the following example:

int len1 = strlen(argv[1]);
int len2 = strlen(argv[2]);

char *word1 = malloc(sizeof (char) * (len1+1) ); // dynamic memory allocaion
char word2[len2+1];  // variable length array declaration.
strcpy(word1, argv[1]);
strcpy(word2, argv[2]);

The above example really copies the contents of strings into a different place in memory using the strcpy function. The place in memory has to be 1 char bigger than is needed for the string to keep the trailing '0';

There are multiple other ways in handling strings in 'c'.

Serge
  • 11,616
  • 3
  • 18
  • 28