[英]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. 我的目标是从用户那里接收
_num_of_lines
输入。 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
这将用于定义2D数组
data
的行数,而数组_lines_len
表示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... 我正在尝试为
_lines_len
内存,但我总是得到数组的大小是2,我不明白为什么...
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 (ie two words). sizeof(linesStruct._lines_len)
返回指针的大小(即两个单词)。 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. 但是无论如何,您已经将其存储在
_num_of_lines
。
linesStruct._num_of_lines already tells you the array size. linesStruct._num_of_lines已经告诉您数组的大小。
Variable len will always have the value of 1, because the size of integer pointer is the same as integer. 变量len的值始终为1,因为整数指针的大小与整数相同。
int len = (int) ((sizeof(linesStruct._lines_len))/(sizeof(int)));
Plus, You don't cast the malloc() result . 另外, 您不会强制转换malloc()结果 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.