I read somewhere that i should be able to initialize the array like that. but why isn't it working.
#include<stdio.h>
main()
{
char s[10];
s[10]="pen";
printf("%s\n",s[10]);
}
output: NULL
I read somewhere that i should be able to initialize the array like that. but why isn't it working.
#include<stdio.h>
main()
{
char s[10];
s[10]="pen";
printf("%s\n",s[10]);
}
output: NULL
This is initialization: char s[10] = "pen";
This is assignment (and invalid syntax): s[10]="pen";
Similar syntax but different terms. Initialization is done together with the variable declaration. Generally, initialization could be carried out before the program is launched. Had you for example written const char s[10] = "pen";, then the string could be pre-loaded into the variable before the program starts.
Since s[10]="pen"; is invalid C but your compiler let it through with a warning (which you probably didn't read), consider compiling with stricter compiler settings. On gcc this means compiling with -pedantic-errors -Werror, which I strongly recommend beginners to use.
Strictly speaking this statement
s[10]="pen";
is not an initialization. It is an assignment. You are trying to assign the string literal "pen" having the type char * to a non-existent element of the type char of the array s with the index 10.
So the both these statements
s[10]="pen";
printf("%s\n",s[10]);
invoke undefined behavior.
Pay attention to that arrays have no the assignment operator. Arrays are non-modifiable lvalues. If you will write for example
s = "pen";
the compiler will issue an error.
What you need is the following
char s[10] = "pen";
printf("%s\n",s);
That is in this case the array s will be initialized with elements of the string literal. All elements that do not have a corresponding initializer of the string literal will be zero-initialized.
If to use assignments instead of the initialization then this declaration
char s[10] = "pen";
is equivalent to
char s[10];
s[0] = 'p';
s[1] = 'e';
s[2] = 'n';
s[3] = '\0';
s[4] = '\0';
s[5] = '\0';
s[6] = '\0';`
s[7] = '\0';
s[8] = '\0';
s[9] = '\0';
`