difference between (*)[] and * in C

84 Views Asked by At

would love for some help with understanding the difference between these two lines:

int(*p)[20] = (int(*)[20]) malloc(sizeof(int) * 20);
int* y = (int*)malloc(sizeof(int) * 20);

if I do:

int * tmp = p;
OR
int * tmp = y;

I get the address of the first element in the array/memory allocated.

Would love for some more thorough understanding of what the difference is and when would I use each one of them?

Addition to the question:

is this casting legal? please explain why and if it is legal, what is tmp equal to?:

int(*p)[20] = (int(*)[20]) malloc(sizeof(int) * 20);
int * tmp = (int*) p;

Thanks to anyone that contributes!

Sincerely,

Roe :)

1

There are 1 best solutions below

2
csavvy On

int(*p)[20] is pointer to array of 20 integers

int* y is a pointer to an int.

when you increment p it will be incremented the sizeof(array of 20) integers ( on my system i see the difference of 80 bytes, since int is 4 bytes)

y is incremented just sizeof (int)

#include<stdio.h>
#include<stdlib.h>
int main() {
    int(*p)[20] = malloc(20*sizeof(int));
    int* y = malloc(sizeof(int) * 20);
    int (*pd)[20] =  p+1;
    int *yd = y+1;
    printf("p = %u and p+1 = %u \n", p, pd);
    printf("y = %p and y+1 = %p \n", y, yd);
    return 0;    
}