0

I am trying to store an array of characters on the heap.

The following code works

char *array[3];
*array = new char;

And also the following

char *array[3];
array[0] = new char;

But not the following

char *array[3];
array = new char;

I viewed the contents of *array, array[0] and array. The first and second do not contain valid pointer addresses after assigning using new but the third one does. So what makes the third one not work? How do the other two work while they just seem to store some unknown symbols (such as $,%,-) rather than the actual address of the pointer?

Mo Sanei
  • 445
  • 6
  • 22

1 Answers1

5

Perhaps it will help to elaborate what a char *array[3] is. This is an array of three pointers, which point to characters. That is, array[0], array[1], and array[2] are each pointers to a character. So, *array and array[0] are fine places (and in fact the same place) to store a pointer to a character, but array isn't even a pointer, it is an array, so trying to store a pointer there doesn't make sense.

If you want to store characters in the heap (using a c-style array of characters), you should just do char *array; and then initialize it as array = new char[3];

However, since you are using C++, it is recommended you either use std::string if you are trying to store a string, or std::vector if you want a list of single characters.

Xymostech
  • 9,710
  • 3
  • 34
  • 44
  • Why do they return some weird symbols and not an address even though I stored an address in them? – Mo Sanei Mar 04 '13 at 22:57
  • @MohammadSanei How did you view them? – Xymostech Mar 04 '13 at 22:58
  • I can't type it using my keyboard but it was a string of three weird characters. – Mo Sanei Mar 04 '13 at 23:00
  • @MohammadSanei I mean, what did you do to look at them? `printf`? `gdb`? – Xymostech Mar 04 '13 at 23:00
  • Well, you were probably seeing junk values. When you call `new char`, it initializes memory, but doesn't set it to 0, so you were probably just seeing what was in there before. Also, `std::cout` tries to figure out what kind of value you are trying to print out, so when you do `std::cout << array[0]` it thinks you are trying to print out a c-style string (a `char*`) and thus prints it as a string, not a pointer. – Xymostech Mar 04 '13 at 23:04
  • Thanks! I have another question. How is `*array` a pointer? Why does it seem to me like a dereferenced value of a pointer? – Mo Sanei Mar 04 '13 at 23:08
  • @MohammadSanei See this question: http://stackoverflow.com/questions/4223617/standard-conversions-array-to-pointer-conversion (it answers your question better than I could in a comment) – Xymostech Mar 04 '13 at 23:13
  • Now I get it! `*array` is the same as `array[0]`, and to give an array an address you should give the first element an address. Thanks for your help. – Mo Sanei Mar 05 '13 at 08:25