【问题标题】:Passing and assigning pointer in C在 C 中传递和分配指针
【发布时间】:2014-02-21 02:23:28
【问题描述】:

我在使用指针时无法分配信息。

我无法在readName 函数中分配任何值。你能检查一下我是否正确地分配了结构吗? 或者 有没有其他方法可以做到这一点而不改变敲击和函数参数?

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
}

【问题讨论】:

  • 你需要为info[]声明一个大小。
  • strcat() on info 没有明显的 \0 初始化 info
  • “双指针”可能意味着指向 double 的指针或指向某事物的指针。按照惯例,它通常被理解为前者。如果这不是您想要的,请编辑您的问题以重新表述。

标签: c pointers struct pointer-to-pointer


【解决方案1】:
  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]或更高的下标。如果你想要超过 1 个指向 name 的指针,你必须为指针分配空间,然后让指针指向一些有效的内存。

试试这个

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 并重试

【讨论】:

  • 是的,我将 ncards 编辑为 Data->n,因为这是我需要的指针数量。我被分配了 1 个指针,因为我现在只需要一个,并计划稍后重新分配。你能告诉我我应该在readName 函数中有什么吗? (*名称)->数字 = 1; //这对我不起作用
  • @user3335341 不确定您在读取名称函数中的确切意图,如果您提供可编译的示例代码,也许我可以查看并检查错误。
  • @user3335341 将 name** const names 更改为 name** names 这可能是问题所在。
  • 我得到了一个函数,但不能对参数做任何事情。在readName 函数中,我想从文件输入中读取名称并将其存储到name.info 中。 name.number是文件中名字的个数
猜你喜欢
  • 2017-01-03
  • 1970-01-01
  • 2012-03-15
  • 2013-04-03
  • 1970-01-01
  • 2020-08-16
  • 2015-02-11
  • 2021-11-12
  • 2012-12-29
相关资源
最近更新 更多