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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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]);

3 Comments

Undefined behaviour, starts from a[1]
a[1], [2], etc are not initialized.
they are! see, I've added comma after each word

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.