I just started to study C, and when doing one example about passing pointer to pointer as a function's parameter, I found a problem.
This is my sample code :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int* allocateIntArray(int* ptr, int size){
if (ptr != NULL){
for (int i = 0; i < size; i++){
ptr[i] = i;
}
}
return ptr;
}
void increasePointer(int** ptr){
if (ptr != NULL){
*ptr += 1; /* <----------------------------- This is line 16 */
}
}
int main()
{
int* p1 = (int*)malloc(sizeof(int)* 10);
allocateIntArray(p1, 10);
for (int i = 0; i < 10; i++){
printf("%d\n", p1[i]);
}
increasePointer(&p1);
printf("%d\n", *p1);
p1--;
free(p1);
fgets(string, sizeof(string), stdin);
return 0;
}
The problem occurs in line 16, when I modify *ptr+=1
to *ptr++
. The expected result should be the whole array and number 1 but when I use *ptr++
the result is 0.
Is there any diffirence between +=1
and ++
? I thought that both of them are the same.
string
. – SainallocateIntArray
is a bad name as it seems youmalloc
the array from the function, but you don't. I suggestfillIntArray
instead. 2) You don't utilize the return value ofallocateIntArray
. I suggest you change the return type tovoid
. 3) Shouldn'tif (ptr != NULL)
in functionincreasePointer
beif (*ptr != NULL)
? 4) The cast inmalloc
is unneccessary. See Sourav's comment above. 5) This:for (int i = 0; i < 10; i++){ printf("%d\n", p1[i]); }
andprintf("%d\n", *p1); p1--;
needs to be enclosed inif(p1 != NULL)
. 6)string.h
is unused. – Sainp+=1
is like++p
, not likep++
– Augustin