cs276
cs276

Reputation: 21

C string setting character array to argv[1]

if I have a program as follows:

int main(int argc, char** argv) {
    char s[32] = argv[1];
    printf("entered char is %s\n", s);
}

Why do I get an error: array initializer must be an initializer list or string literal, during compile time?

Isn't argv[1] a string and isn't is legal to do

char s[32] = "A test string"

Upvotes: 2

Views: 561

Answers (3)

user2736738
user2736738

Reputation: 30926

Asking a question like this means - you are not aware of certain rules. In C, there are a few possible ways you can initialize an array. And the compiler told you about that when it saw it violating the rule. It says it must be string literal or initializer list. The one you provided is not any of this. It is simply a pointer and you can't initialize an array by putting it in the right side of the = assignment operator.

char s[]="hello";
char s[]={'h','e','\0'};

Select one as shown above. First is using literal and second using initializer list. In your case you can't use any of these - what's the way? strcpy at your rescue. Before you use like the other answer showed make sure buffer is big enough to hold stuff you copy.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409196

You can't initialize an array using a pointer like that. Instead you have to copy the string after declaration:

char s[32];
strcpy(s, argv[1]);

Note that you should really check if at least one argument is provided before doing that (by checking argc). Also note that unless you want to modify the string provided in the argument, there's really no need to keep a second copy of the string.

Oh and you might want to use strncpy instead of plain strcpy, to avoid a possible buffer overflow situation. Remember that strncpy will not terminate the string if the source is to long, so you need to do it explicitly.

Upvotes: 4

Achal
Achal

Reputation: 11921

Expression char s[32] = argv[1]; causes error because by doing s=argv[1] you are trying to change base address of s, which is not possible as s is constant pointer.

Use strcpy() to copy argv[1] into s

char s[32];
strcpy(s,argv[1]);

Upvotes: 1

Related Questions