Why is the operator (*
) needed to access the value of an int*
variable but not for char*
?
char *char_ptr;
int *int_ptr;
int mem_size = 50;
char_ptr = (char *) malloc(mem_size);
strcpy(char_ptr, "This is memory is located on the heap.");
printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);
int_ptr = (int *) malloc(12);
*int_ptr = 31337;
printf("int_ptr (%p) --> %d\n", int_ptr, *int_ptr);
Output:
char_ptr (0x8742008) --> 'This is memory is located on the heap.'
int_ptr (0x8742040) --> 31337
This is because of the way the printf
format specifiers work: the %s
format expects, for its corresponding argument, a pointer to a character (more precisely, the address of a nul
-terminated string - which can be an array of char
, an allocated buffer with at least one zero byte in it, or a string literal), so you can just give it the char_ptr
variable as-is; on the other hand, the %d
format expects an integer (not a pointer-to-integer), so you have to dereference the int_ptr
variable using the *
operator.
Note on Good Programming Style: As mentioned in the comments to your question, be sure to call free()
at some point on every buffer allocated with malloc
, or you will introduce memory leaks into your code. Also see: Do I cast the result of malloc?.
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