1

I have a problem here. I'm unable to get how many pointers are there in one row of 2D array of strings. Error says:

division ‘sizeof (char **) / sizeof (char *)’ does not compute the number of array elements [-Werror=sizeof-pointer-div]

I understand what we need to do to get the number, but somehow I can't divide the bytes :/.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>    
    int main()
    {
        char ***array;    
        array = malloc(1* sizeof(char**));    
        array[0] = malloc(5 * sizeof(char*));    
        size_t size = sizeof array[0] / sizeof(char*); //error
        printf("%lu\n", size);
        return 0;
    }
Momoos
  • 27
  • 6

1 Answers1

1

This approach works fine with static arrays, but fail on dynamic ones as you are calculating 'sizeof (*array) / sizeof(*char) // 8 / 8` will always be 1.

I'd suggest defining the sizes and using them accordingly

#define MAX_HEIGHT 10
#define MAX_WIDTH 10

...

array = malloc(MAX_HEIGHT * sizeof(char**));
// do not forget to test the malloc result     
if (!array) // do something

for (int i = 0; i < MAX_HEIGHT; i++){
     array[i] = malloc(MAX_WIDTH * sizeof(char*));
     if (!array[i]) // do something
}

height = MAX_HEIGHT;
width = MAX_WIDTH;

// from here you can allocate the strings and run some code with the base size
ACoelho
  • 341
  • 1
  • 11
  • 1
    Oh, well, but I need to use a dynamic array. Thank you. – Momoos Dec 01 '20 at 15:40
  • So this is the way to go, static arrays are great in a few cases, but you will usually use the dynamic ones, and some practices are different, such as how to get the size of the array. – ACoelho Dec 01 '20 at 15:41