3

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 \ns by \ts then output changes like

"U s HelloThisisatest (null)"

why?

Donato Szilagyi
  • 4,279
  • 4
  • 36
  • 53
fuzzy
  • 229
  • 1
  • 4
  • 15

3 Answers3

11

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.

phoxis
  • 60,131
  • 14
  • 81
  • 117
1

You have an array of pointers to char. However, there is only one such pointer, so code like:

a[1][0]

overruns the array. The first index must always be 0 for this particular array.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
1

you may want to do this:

char a[][20] = {"Hello", "This", "is", "a", "test"};

notice that the second dimension should have a size (20)

now you can print all the words:

printf("%s\n",a[0]);
printf("%s\n",a[1]);
printf("%s\n",a[2]);
printf("%s\n",a[3]);
printf("%s\n",a[4]);
phoxis
  • 60,131
  • 14
  • 81
  • 117
arash kordi
  • 2,470
  • 1
  • 22
  • 24