2
char p[3][6]={{'a','b','c','\0'},{'d','e','f','\0'},{'g','h','i','\0'}};
char s[3][6]={"abc","def","ghi"};

Are they both same? If different please explain what way and how it is stored in memory?

10
  • 4
    The difference is the first one doesn't compile: ideone.com/QrxZff. Commented Jun 2, 2013 at 2:12
  • 2
    he meant char p[3][6]={{'a','b','c','\0'},{'d','e','f','\0'},{'g','h','i','\0' }}; I think. Commented Jun 2, 2013 at 2:14
  • 1
    @OliCharlesworth That's because you're too strict: C89 compiles it just fine, but it produces garbage output. Commented Jun 2, 2013 at 2:19
  • 1
    @dasblinkenlight: That's not C89, that's just lack of -Wall... Commented Jun 2, 2013 at 2:21
  • 1
    Now the question has been edited, the answer is: they are the same. Commented Jun 2, 2013 at 2:22

2 Answers 2

3

They're the same in memory. Here in the VS 2010 debugger, I cast to char* so I can inspect the first 18 raw bytes of p and s: screenshot of program in Visual Studio

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

Comments

2

There is no difference in any of two methods, Try the following code and see the result
Result for both variables p and s are same.

  • In first definition you've provided string in the form of array of characters by using Single Quotes.
  • Whereas in Second definition you've provided direct string by Double quotes - Both are same

  #include<stdio.h>
    void main()
    {
        int i,j=0;
        char p[3][6]={{'a','b','c','\0'},{'d','e','f','\0'},{'g','h','i','\0'}};
        char s[3][6]={"abc","def","ghi"};
        for(i=0;i<3;i++)
        {
            printf("%s",p[i]);
            printf("\n");
        }
        for(i=0;i<3;i++)
        {
            printf("%s",s[i]);
            printf("\n");
        }
    }

Here is the result:

First 2-d string is : abc        def     ghi
Second 2-d string is :abc        def     ghi

3 Comments

but, char *c[3] = { "abc", "def", "ghi" }; is different. Worth noting.
Yes, If you are talking about this pointer array to character, then you are right.
ya understood. thanks. what will happen if i dont give'\0' in the first statement

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.