Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing array of chars using pointer to char

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?

like image 390
user2648841 Avatar asked Feb 23 '26 11:02

user2648841


1 Answers

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) { . . . }
like image 148
E. Moffat Avatar answered Feb 25 '26 01:02

E. Moffat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!