我在使用指针时如何分配信息时遇到麻烦。
我不能在readName
函数中分配任何值。可以检查我是否正确分配了结构吗?
要么
是否有另一种方法可以执行此操作而又不更改Struck和function参数?
typedef struct name
{
char info[];
int number;
//some more codes
} name;
typedef struct Data
{
name ** n;
//some more codes
} Data;
int readName(FILE *const fp, name **const names)
{
(*names)->number = 1; // no idea what to put here to store
strcat ((*names)->info, "aBC");
//codes
}
int read(FILE *const fp, Data *const data)
{
data->n = malloc(sizeof(name*)*1); // am I mallocing correctly?
data->n[0]=malloc(sizeof(name));
i = readName(fp, &data->n[Data->n]);
//codes
}
int main ()
{
Data * d;
d = malloc (sizeof (Data));
i = read(fp, d); //assume fp is decleared
//codes that usses the struct
}
最佳答案
data->n = malloc(sizeof(name*)*1); // am I mallocing correctly?
data->n[0]=malloc(sizeof(name));
您只为1个指针
data->n = malloc(sizeof(name*)*1);
分配了空间,因此您有1个指向名称结构的指针。i = readName(fp, &data->n[filep->ncards]);
但是执行上述操作后,您只能执行
&data->n[0]
,不能执行&data->[1]
或更高版本的下标。如果要使用多个指向名称的指针,则必须为该指针分配空间,然后使该指针指向一些有效的内存。尝试这个
data->n = malloc((struct name*)how many pointers you want);
for(int i =0;i<how many pointers you want;i++)
data->n[i] = malloc(sizeof(struct name));
从您的代码开始,因为它还不完整,我认为ncards =您想要多少个指针。
int readName(FILE *const fp, name **const names)
try
int readName(FILE *const fp, name ** names)
您将无法通过const **指针更改数据,删除const并重试
关于c - 在C中传递和分配指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21924022/