簡體   English   中英

為結構中的數組動態分配內存的C語言

[英]C dynamic allocating memory for array within a struct

首先,我定義了這個結構:

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

我的目標是從用戶那里接收_num_of_lines輸入。 這將用於定義2D數組data的行數,而數組_lines_len表示data中每行的長度

我正在嘗試為_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)返回指針的大小(即兩個單詞)。 實際上,沒有辦法在編譯時靜態確定數組大小。 但是無論如何,您已經將其存儲在_num_of_lines

linesStruct._num_of_lines已經告訴您數組的大小。

變量len的值始終為1,因為整數指針的大小與整數相同。

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

另外, 您不會強制轉換malloc()結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM