Can i use the following code or it's incorrect?

73 Views Asked by At

Well first i'm using language c i still a beginner.

char S[20];
S ="ewer" ;

is that correct.

3

There are 3 best solutions below

0
On

Arrays (including strings) can't be assigned in C. For strings you need strcpy, or preferably strncpy:

#include <string.h>

...

char S[20];

strcpy(S, "ewer");             // strcpy is fine for this example

strncpy(S, "ewer", sizeof(S)); // strncpy is safer in general and
                               // should be preferred over strcpy
0
On

No, that won't work.

The variable S is an array, and you can't assign to arrays like that in C. The string "ewer" is represented as an array of characters terminated by the character '\0'. To copy it into the array, you need to use a function:

strcpy(S, "ewer");
1
On

That's a good question. In fact, if you'd wrote char* S instead, the example would worked. You might be confused by the fact, that arrays and pointers have many alike things — like [] operator.

But you must understand that array is different from a pointer. One of the main differences is that you couldn't increment an array, like ++myArr (this code okay for pointer, but not for an array). The other one you see in the question: you can not reassign an array variable to point another array. That is exactly what you're trying to do: you're assigning to the array variable S a pointer to a place with the text "ewer", that won't work.

Assuming that you wanted to assign to an array the text, you could do the following:

char S[] = "ewer";

Here you say to the compiler to allocate as much space on the stack, as the "ewer" text (plus the zero end character) holds, and copy that text there. Notice the empty braces [] — you don't even need to manually count symbols, it would be done for you by a compiler.