Changing the value of a pointed to integer in C
I want to declare a new integer in the heap,
int *intPtr = 开发者_C百科(int*) malloc(sizeof(int));
How do I change the value of the space in the heap, to which *intPtr
points to?
Thanks
Dereference intPtr
:
*intPtr = 0;
First of all, you don't need to cast the result of malloc. malloc returns a void* and the void* is casted implicitly to any pointer (int*, char*, ...).
So :
int *intPtr = malloc(sizeof(int));
You can also write :
int *intPtr = malloc(sizeof *intPtr);
If you want to change the value pointed by intPtr, just use the dereference operator '*' like :
*intPtr = <new_value>
where is your new integer value.
精彩评论