1

Full disclosure: This is homework. I'm just really confused about one part. I have this code in a c++ program:

char * charArray = new char[100];

//fill charArray 
char c = '.';
for(int i=0; i<100; i++)
{
    charArray[i] = c;
    c = c + 1;
}
cout <<"Char Array: " << endl;
for(int i=0; i<100; i++)
{
    cout << "Type: Char @ " << &charArray[i] << " = " << charArray[i] <<endl;
}

At a different point in my program I have pretty much the exact same code but instead of a char array it is a float array. When I print out the float array I get Type: Float @ whatAppearsToBeAProperMemoryAddress = correctFloat#.

However although the chars are correct the address don't appear to be. The address for the char array go like this: ./0123456789<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~?????????????????? /0123456789<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~??????????????????

.... all the way to ?? ?

So obviously instead of getting the address I am getting varying degrees of what should be the contents of the array. I am very confused and any pointers would be appreciated. This is my first crack at c++.

MichelleJS
  • 759
  • 3
  • 16
  • 32

1 Answers1

3

Because &charArray[i] is still a char* pointing to the ith character of the string. So it is used as a whole string. Try to cast as this:

(void*)&charArray[i]

that is the same as:

(void*)(charArray+i);
Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
  • I'm going to mark your question as correct because it worked perfectly thanks. However you said &charArray[i] is still a char * pointing to the ith character of the string. I'm confused as to why if it is pointing t the ith character of the string it is printing the whole really long string? I hope that makes since and sorry if its a dumb question. – MichelleJS Oct 24 '13 at 05:21
  • 1
    @MichelleJS it prints from the `i`th character until it finds a `\0`. This is what output streams do when they are given a `char*`: they assume it is the beginning of a null-terminated string. – juanchopanza Oct 24 '13 at 05:33
  • @juanchopanza - Thanks. That makes tons more sense now. – MichelleJS Oct 24 '13 at 05:36