-5

Possible Duplicate:
What is the difference between char a[] = “string”; and char *p = “string”;

Could you please explain what is the difference between these? ^^

            //difference between:
            char* sz1 = "blah";
            char  sz2[] = "blah";

            //and also please explain these
            char *sz3 = new char[512];
            char *sz4[512] = { 0, };
            char sz5[512];
Community
  • 1
  • 1
Vinicius Horta
  • 233
  • 2
  • 13

2 Answers2

2

"blah" is a const char [5]. In the first line, that array is decayed into a pointer to be stored in your variable as a pointer to the first element. It is also a pointer to non-const characters that points to const characters. It should be:

const char *sz1 = "blah";

In the second (thanks jrok), it creates an actual array and initializes it with {'b', 'l', 'a', 'h', '\0'}.

char *sz3 = new char[512];

This allocates 512 * sizeof (char) bytes of memory for the chars and sz3 will point to the beginning. This is stored on the heap, as opposed to the stack, so don't forget to delete[] it.

char *sz4[512] = { 0, };

This creates an array of 512 pointers to characters and initializes them all to 0 (NULL). The comma isn't needed, it's just easier to add onto the initializer list afterwards. The spiral rule can be used here to determine sz4 is an array of 512 (one right) pointers (one left) to char (two left).

char sz5[512];

This creates an array (on the stack) of 512 characters.

All but the second-last can effectively be replaced with std::string.

chris
  • 60,560
  • 13
  • 143
  • 205
-1

The First two examples are essentially the same, char pointers with memory assigned to them at runtime.

The third one, you are allocating 512 bytes worth of memory and assigning sz3 the address of it.

For the fourth one you are declaring an array of 512 char pointers, but your assignment (to the best of my knowledge) is incorrect.

And Finally, the fifth statement creates an array of 512 chars.

Whyrusleeping
  • 889
  • 2
  • 9
  • 20