In the following code I am having the output like(last one giving segmentation fault)
U
s
HelloThisisatest
Segmentation fault (core dumped)
but i do not understand why. code is
int main()
{
char *a[]={"Hello" "This" "is" "a" "test"};
printf("%c\n",a[1][0]);
printf("%c\n",a[0][8]);
printf("%s\n",a[0]);
printf("%s\n",a[3]);
return 0;
}
Another question is that can we initialize an 2-D array without using comma?
Another situation that I got that when i am replacing the \n
s by \t
s then output changes like
"U s HelloThisisatest (null)"
why?
This is because in C, two adjacent strings are concatenated into one. So "Hello" "World" is actually a single string "HelloWorld".
In your case The array of pointer actually contains one single string "HelloThisisatest". In the first printf you are accessing the location 1, which is undefined behaviour.
The next printf accesses the character 8 of the string which is s
.
The third printf prints the entire string stored on the location 0
, which is "HelloThisisatest"
The last printf attempts to access the array location 3, which is undefined behavour, as it is not initialized.
EDIT
Refer C11/C99 standard Section 5.1.1.2 Paragraph 6, which tells:
Adjacent string literal tokens are concatenated.