Home > database >  malloc and array in C
malloc and array in C

Time:01-02

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?

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related