Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation for pointer to an array in c?

#include <stdio.h>
int main()
{
 int (*ptr) [5];
 printf ("%lu\n" , sizeof (ptr));
 printf ("%lu\n" , sizeof (*ptr));
}

I am using 64 bit system. When I run this code in gcc compiler it generate output 8 and 20 . My question is how many byte going to allocate for this pointer to an array ? It is 8 or 20 and why?

like image 865
Baranitharan Avatar asked Jun 20 '26 06:06

Baranitharan


2 Answers

My question is how many byte going to allocate for this point to an array ? It is 8 or 20 and why?

It depends on if you need to allocate memory for a pointer or for the memory it's pointing at.

You need to know the sizes of what you are looking at:

#include <stdio.h>

int main() {
    int(*ptr)[5];
    
    printf("%zu\n", sizeof ptr);     // size of a pointer - expression sizeof
    printf("%zu\n", sizeof(void*));  // size of a pointer - type sizeof
    printf("%zu\n", sizeof *ptr);    // size of an int[5] - expression sizeof
    printf("%zu\n", sizeof(int[5])); // size of an int[5] - type sizeof
}

Sidenote: %lu is not the correct conversion. Use %zu for sizeof.

like image 188
Ted Lyngmo Avatar answered Jun 21 '26 20:06

Ted Lyngmo


You declare ptr to be a pointer to an array of 5 integers. ptr holds the address which is 8 Bytes.

When you look up what is at the address (dereferencing) with *ptr you get the array of 5 integer which is 5*sizeof(int) = 5*4 = 20

Caution: There may be an address in ptr but there is no memory allocated at that address.

To do this you need to call ptr = malloc(sizeof(*ptr))

If you don't do this, access to the array will segfault. For example *ptr[0]=0;

like image 37
GuentherMeyer Avatar answered Jun 21 '26 20:06

GuentherMeyer



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!