2014-02-21 68 views
0

我在使用指针时如何分配信息有问题。传递和分配指针C

我不能在readName函数中分配任何值。你能检查我的malloc结构是否正确吗? 或 有没有另一种方法来做到这一点,而不改变敲击和函数参数?

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 
} 
+3

你需要声明一个大小'信息[]'。 – Barmar

+1

'info'上的'strcat()'没有明显的'\ 0'初始化'info'。 – chux

+0

“双指针”可能意味着指向“double”或指向某个指针的指针。按照惯例,它通常被理解为意味着前者。如果这不是你想要的,请编辑你的问题来重新修改。 – keshlam

回答

0
data->n = malloc(sizeof(name*)*1); // am I mallocing correctly? 
    data->n[0]=malloc(sizeof(name)); 

你只有1个指针data->n = malloc(sizeof(name*)*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) 

您将无法通过一个常量来改变数据**指针,取出常量,然后再试一次

+0

是的,我编辑数据 - > n,因为那是我需要多少指针。 我被分配了1个指针,因为我现在只需要一个指针,并且计划稍后重新分配。 你能告诉我我应该在'readName'函数中做些什么吗? (*名称) - > number = 1; //这对我不起作用 – user3335341

+0

@ user3335341不确定你的意图是在读取名称函数中,如果你提供了一个示例代码来编译,也许我可以看看并检查错误。 – tesseract

+0

@ user3335341将名称**常量名称更改为名称**名称,这可能是问题所在。 – tesseract