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);
3
  • 2
    sizeof on a pointer returns the size of the pointer, not the buffer that follows it. Commented Oct 28, 2013 at 17:39
  • sizeof(linesStruct._lines_len) returns the size of memory for an int *, not the length of your array. Commented Oct 28, 2013 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? Commented Oct 28, 2013 at 17:43

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.