문제

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);
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top