0
I have a problem with sizeof(*ptr)=4, when execute this code.but,I have included 3 assign values to that pointer.Explain this!!
#include <stdio.h> #include <stdlib.h> //realloc(ptr,bytes) int main() { int *ptr; ptr=malloc(10*sizeof(*ptr)); if (ptr!=NULL) { *(ptr+5)=67; } ptr=realloc(ptr,100*sizeof(*ptr)); *(ptr+60)=56; *(ptr+67)=44; printf("%d %d ",*(ptr+5),*(ptr+60)); printf("%d ",sizeof(*ptr)); }
3 ответов
+ 1
Lorshan , when you print the size of *ptr it will print the size of data type of that pointer.
Run below code,
int *ptr;
char *pt;
printf("%ld %ld\n",sizeof(*ptr), sizeof(int));
printf("%ld %ld",sizeof(*pt), sizeof(char));
+ 1
ptr is a pointer to a block of memory allocated by malloc (a.k.a an array). *(ptr + 5) = 67 is the same as the array subscript version ptr[5] = 67. The pointer holds the base address to the memory block and you're assigning values to the memory area offset by N steps past the base address. So the pointer itself is not holding 3 values, but the memory block it points to does.
sizeof(*ptr) doesn't yield the size of the pointer but the size in bytes of what the pointer points to, which is an integer.
There are two issues:
You should not directly assign the return of realloc() to your pointer variable because it may return NULL on failure. If it does you will leak memory. Use a temporary variable to hold the return value and assign it to ptr if realloc() succeeds.
The return type of sizeof() is size_t which is printed using the %zu specifier since C99 and %lu for C89. %d is for integers.
0
Here is code with some changes to remove error and warnings.
#include <stdio.h>
#include <stdlib.h>
//realloc(ptr,bytes)
int main()
{
int *ptr;
ptr=(int*)malloc(10*sizeof(*ptr));
if (ptr!=NULL)
{
*(ptr+5)=67;
}
ptr=(int*)realloc(ptr,100*sizeof(*ptr));
*(ptr+60)=56;
*(ptr+67)=44;
printf("%d %d ",*(ptr+5),*(ptr+60));
printf("%ld ",sizeof(*ptr));
}