I have a question regarding pointers. When I iterate through a char array using pointer to char array in function, original array stays the same, but when I do it in main function, I can't print char array.
I am new to pointers.
void f(char* a)
{
while (*a!=0) {
*(a++); // going through array
}
}
int main()
{
char* a1 = "test";
f(a1);
cout <<a1<<endl; // I can normally print out "test"
return 0;
}
But,
int main()
{
char* a1 = "test";
while (*a1!=0) {
*(a1++);
}
cout <<a1<<endl; // won't print anything
return 0;
}
So my question is, even though I am passing pointer to function, why is original array not modified?
Since you're incrementing the pointer a1, it points to the character '\0' at the end of the loop in main. Printing a null character prints nothing (empty string).
When you do this with a function, the pointer a is local is local to the function. It is modified within the function but is not changed in main. If you wanted similar results between the two examples, you would have to change the function to accept a reference parameter to the pointer:
void f(char * &a) { . . . }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With