Search code examples
carraysdynamic-data

C dynamic allocating memory for array within a struct


First I defined this struct:

typedef struct{
    int **_data;
    int _num_of_lines;
    int *_lines_len;
} Lines;

my goal is to receive _num_of_lines as input from user. which will be used to define number of line of the 2D array data whereas the array _lines_len repreasants length of each line in data

I'm trying to malloc memory for _lines_len, but I always get back that the size of the array is 2, and I don't understand why...

int main(int argc, char *argv[]) {
    Lines linesStruct;
    printf("enter num of lines:\n ");
    scanf("%d",&linesStruct._num_of_lines);
    printf("Num of lines is = %d \n", linesStruct._num_of_lines);

    linesStruct._lines_len = (int*) malloc(linesStruct._num_of_lines * sizeof(int));
    int len = (int) ((sizeof(linesStruct._lines_len))/(sizeof(int)));
    printf("number of lines len = %d \n", len);

Solution

  • sizeof(linesStruct._lines_len) return the size of the pointer (i.e. two words). There's really no way to statically determine the array size at compile time. But you've got that stored in _num_of_lines anyway.