[英]Dynamic array in structs
我在 C 中使用動態 memory 時遇到問題。 我正在創建一個結構,其數據是一個數字和一個指向另一個結構的指針(簡而言之,一個結構數組)。 目標是讓父結構使用動態 memory 存儲另一個結構的數組。
我遇到的問題是訪問創建的數組的單元格,因為我不知道這是由於語法問題(我是 C 新手),還是我創建的數組錯誤,我無法修改包含在父結構內包含數組的每個單元格中的信息。 我只能默認修改第一個單元格。
這是我的代碼,任何想法或建議將不勝感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char string[64];
void* date;
void* colour;
} DataState;
typedef struct {
int number;
DataState* array;
} Book;
Book* makeBook (int number){
int a=5;
void* auxiliary=&a;
Book* book_A=(Book*)(malloc(sizeof(Book)));
book_A->number=number;
book_A->array=(DataState*)(malloc(number*sizeof(DataState))); //creating array of structs inside main struct.
//And what I want to do is something like this, modify the information contained in cells of the array of structs of the main struct.
book_A->array[3]->date=auxiliary;
return book_A;
}
從已經非常感謝了。
這里:
book_A->array[3]->date=auxiliary;
您將auxiliary
值分配給數組的第三個元素,但auxiliary
定義為
void* auxiliary=&a;
而a
是 function 中的自動變量。
自動變量在 function 返回時消失,因此一旦執行return
,分配給book_A->array[3]->date
的指針就會失效。
如果您希望保存在a
中的數據在makeBook
返回后仍然有效,那么您必須將其分配到比自動更持久的存儲中。 你基本上已經做到了:
int* foo()
{
int a = 5;
// WRONG, cannot return the address of a local variable
return &a;
}
int main(void)
{
int* a_addr = foo();
// WRONG, invokes undefined behavior
printf("a = %d\n", *a_addr);
}
如果您希望a
在foo
之外持續存在,一個可能的選擇是:
int* foo()
{
int* a = malloc(sizeof *a);
// always check the return value of malloc
if (a != NULL)
{
*a = 5;
}
// this is ok. `a` is still in automatic storage, but this _returns_ its
// value, which is a pointer to data _not_ in automatic storage.
return a;
}
int main(void)
{
int* a_addr = foo();
// still must check here, malloc in `foo` could have failed. Probably
// better to design an architecture where you only check validity once
if (a_addr != NULL)
{
printf("a = %d\n", *a_addr); // prints a = 5
// don't forget to `free(a_addr)` when you're done with it, or you can
// let the OS clean up the memory when the process exits.
}
else
{
// handle error how you want
fprintf(stderr, "Out of mem!\n");
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.