Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

malloc and array in C

I’m learning C, and C is my first programming language. I’ll add code first.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int main() {
    int row = 3, col = 2;

    int(*ptr)[2] = (int(*)[2])malloc(sizeof(int) * row * col);
    if (!ptr) exit(1);
    printf("%d", sizeof(*ptr[0]));
    return 0;
}

4

Maybe, ptr[0] is pointer or array. Should I think ptr[0] as an array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

int (*ptr)[2] declares ptr to be a pointer to an array of two int.

That means *ptr is an array of two int. ptr[0] is effectively the same as *ptr, so it is also an array of two int.

By definition, ptr[0] means to add zero to ptr and then apply *. Adding zero does not change the value, so ptr[0] is effectively *ptr.

Setting ptr to (int (*)[2]) malloc(sizeof(int) * row * col); sets it to point to memory that can be used as 3 arrays of 2 int (because row is 3 and col is 2). So those three arrays are ptr[0], ptr[1], and ptr[2].

Since each of those is an array of two int, they each have two elements, which can be accessed as ptr[0][0], ptr[0][1], ptr[1][0], ptr[1][1], ptr[2][0], and ptr[2][1].

Note that the subscript operator, [ … ], can be used with pointers or arrays. In either case, E1[E2] is defined to be *((E1) + (E2)). With a pointer, this addition operates in units of the pointed-to type. When E1 is a pointer to an array of two int, adding 1 or 2 produces a pointer that points 1 or 2 arrays of two int further along in memory (as long as the arithmetic remains in bounds of the applicable space). When E1 is an array, it is automatically converted to a pointer to its first element, and then the arithmetic proceeds as for a pointer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading