Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between char pointer and char array

I have defined 2 variables, one a pointer and one an array

char* ptr;
char* array;

ptr = "12345";
array = new int[5];

for(int i = 0; i < 5; i++)
    array[i] = i;

while(*ptr != 0)
        cout << *ptr++ << endl;

//Get garbage values
for(int i = 0; i < 5; i++)
    cout << ptr[i];

I was wondering what are the major differences between the variables. And why I get garbage values when I try to print the values in "ptr[]" the array way, but it's perfectly fine when iterate through the vales. I can't seem to understand how my variable "ptr" can point to 5 characters, since it should only be able to point to one.

like image 550
Josh Avatar asked Apr 21 '26 16:04

Josh


1 Answers

There are many differences between pointers and arrays, but the reason you are getting garbage, is that by the time you use ptr with an index, it already points to the null terminator of "12345".

Everytime you do this:

*ptr++;

ptr points to the next element it used to point (i.e. 1, 2, 3, ...). When the loop ends, it points to the null terminator \0 and then when you try to index it with i, it points to unknown memory.

I suggest you use a temp pointer to iterate through the elements instead:

const char* ptr; // declaring ptr constant in this case is a good idea as well

...

ptr = "12345";
char *tmp = ptr;

...

while(*tmp != 0)
    cout << *tmp++ << endl;
like image 90
imreal Avatar answered Apr 23 '26 07:04

imreal