-
help with pointers/chars
ok i need help. read the code
Code:
#include <iostream>
using namespace std;
int main()
{
const int MAX = 80;
char buffer[MAX];
char* pbuffer = buffer;
int i =0;
cin.getline(buffer, MAX, '\n');
while(*pbuffer)
{
pbuffer++;
}
cout << "num of chars in buffer is " << (pbuffer - buffer);
return 0;
}
why is (pbuffer - buffer) the number of characters in the buffer array. i know at the end of the program execution pbuffer has the address of '\0', but why does subtracting the address of '\0' to the buffer array equal the number of characters in the buffer array?
please do tell.!!!
-
In the beginning you set pbuffer and buffer to the same memory address.
Then you put a string there ( so therefore pbuffer and buffer are both the address of the first char )
then you changed pbuffer to the address of end of the string ( with the while loop )
so you were just cout'ing the differnence in the address of the beginning of the string and the end of the string.
-
also another question
why does this work
Code:
char *pbuffer = NULL;
cin >> pbuffer;
cout << pbuffer;
and this doesnt work
Code:
char *pbuffer = NULL;
cin.getline(pbuffer, 80, '\n');
please explain...!
-
omg..thanks for clearing up for the first question..i thought the pepsi was getting to me...hehe...i havent sleep for almost a day..
-
so...
char* string = "blah";
creates a literal string "blah" and stores it in a const char array which i cannot do string = "blah3" because string is pointing to the address of "blah" and i cannot make it point to "blah3" because there is no memory location of "blah3". if this is correct. thanks i understand now.....if now please explain further
-
Code:
char * s = "hello"; /* compiler allocates "hello" off the stack and points 's' at it. */
s = "world"; /* no problem, compiler cleans up stack literal "hello" */
char * t = s; // fine
strcpy(t, "bye"); // crash! "world" is const!
So in other words, the pointer is not const here, the literal itself is.
-
Ah, thanks for setting me straight Salem!