0

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);
lurker
  • 56,987
  • 9
  • 69
  • 103
sony jimbo
  • 39
  • 5
  • 2
    `sizeof` on a pointer returns the size of the pointer, not the buffer that follows it. – Kninnug Oct 28 '13 at 17:39
  • `sizeof(linesStruct._lines_len)` returns the size of memory for an `int *`, not the length of your array. – lurker Oct 28 '13 at 17:40
  • hmmm I don't quite get it then, how do I figure out what is the length of the array after the allocation? – sony jimbo Oct 28 '13 at 17:43

2 Answers2

1

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.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
0

linesStruct._num_of_lines already tells you the array size.

Variable len will always have the value of 1, because the size of integer pointer is the same as integer.

int len = (int) ((sizeof(linesStruct._lines_len))/(sizeof(int)));

Plus, You don't cast the malloc() result.

Community
  • 1
  • 1
Algo
  • 841
  • 1
  • 14
  • 26