0

my requirement is to allocate a 2d char array in c language lets say of size 10 such that if I want to get its size later, I should get 10 as answer.

But I am stuck with 2 approaches both having some problems..

**Approach 1 **(Problem in getting actual size/number of rows)

char **arr = NULL;
arr = (char **)malloc(sizeof(char *) * 10);
int sz = sizeof(arr) / sizeof(arr[0]); //expected 10, but gives 8 (that is size of char ptr(8) / sizeof char   (1))

Approach 2 (don't know malloc for this)

char *arr[] = {};
//malloc to allocate 10 rows
int sz = sizeof(arr) / sizeof(arr[0]);  // gives 10 correctly

2 Answers2

4

char **arr = NULL; is not 2D array only a pointer to pointer to char. sizeof will not work on a pointer to pointer the same way as you use it for a "normal" array to get its size.

When you dynamically allocate the array you need to remember the size of the array yourself. sizeof will not work in this case.

How to allocate real 2D array? You need to use pointers to arrays.

size_t rows = 10;
size_t columns = 20;

char (*Array2D)[columns] = malloc(rows * sizeof(*Array2D));
0___________
  • 60,014
  • 4
  • 34
  • 74
  • It is unclear to me if the OP means dynamic allocation or just definition, such as `char array[2][5]` for which `size(array)` does evaluate to `10`. – chqrlie Mar 22 '23 at 16:53
  • `Array2D` is not a not a _2D array_ either. `Array2D` is a pointer, a pointer to a 1D array. – chux - Reinstate Monica Mar 22 '23 at 17:05
  • So "rows" value can't be hardcoded/known beforehand. It would be received from user input and based on that 2D char array should be allocated. Columns can be fixed before hand. – Aryan Maheshwari Mar 22 '23 at 17:18
1

The following code does what you asked for but not what you probably actually want. In particular, the pointer cannot be passed out of the routine in ordinary ways.

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


void foo(size_t n)
{
    int (*p)[n] = malloc(sizeof *p);
    if (!p)
    {
        fprintf(stderr, "Error, malloc failed.\n");
        exit(EXIT_FAILURE);
    }

    printf("*p has %zu elements.\n", sizeof *p / sizeof **p);
}


int main(void)
{
    foo(3);
    foo(10);
}

It works because, while we must assign the result of malloc to a pointer, not an array, it can be a pointer to array type, and that type may be a variable length array type.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312