Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - incrementing array pointer

Tags:

arrays

c

pointers

Can someone explain to me why this doesn't work. I'm java developer and new to c/c++
As far as i understood pointer of array is actually pointer of arrays first element, is that correct?

void test(char *tmp)
{
    test2(tmp);
    //*tmp++ = '1';
    //*tmp++ = '2';
    *tmp++ = '3';
    *tmp++ = '4';
    *tmp = 0;
}

void test2(char *tmp)
{
    *tmp++ = '1';
    *tmp++ = '2';
}

int main(int argc, char **argv)
{
    char tmp[5];
    test(tmp);
    printf("%s", tmp);
    return 0;
}

only 34 gets printed. When i debug this code in function test2 pointer of tmp is incremente by one but back in function test after test2 is called, pointer of tmp is back to its initial value.
If i just put all of the code in single function like this, it works:

void test(char *tmp)
{
    *tmp++ = '1';
    *tmp++ = '2';
    *tmp++ = '3';
    *tmp++ = '4';
    *tmp = 0;
}

Also what does the *tmp = 0 on the last line do. I copied it from some other code. Without it there is some junk on the end of the array.

like image 956
pedja Avatar asked Feb 21 '26 14:02

pedja


2 Answers

In function test2, pass-by-pointer means you can modify what tmp points to, but test2 does not modify the pointer itself.

void test2(char *tmp)
{
    *tmp++ = '1';
    *tmp++ = '2';
}

So in the caller function test, after calling test2 the pointer does not move forward by 2 positions as you would expect, instead tmp remains the same (which is pointing the the very first value of the array). So what actually happens is test2 assign 1 and 2 for the first two elements, and then test overwrite those two values with 3 and 4.

void test(char *tmp)
{
    test2(tmp);
    *tmp++ = '3';
    *tmp++ = '4';
    *tmp = 0;
}

Also what does the *tmp = 0 on the last line do.

That's string terminator.

like image 86
artm Avatar answered Feb 23 '26 06:02

artm


Incrementing the 'tmp' in test2() does not increment the 'tmp' in test(). After the test2() call returns, the '1' and '2' written by test2 are overwritten by '3' and '4'.

The zero is the '\0' c-style 'string' terminator.

like image 28
Martin James Avatar answered Feb 23 '26 07:02

Martin James



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!