【问题标题】:passing array (not pointer) to a struct in c将数组(不是指针)传递给c中的结构
【发布时间】:2015-03-24 23:37:06
【问题描述】:

我正在尝试多种方法将数组传递给函数,但它不断确定我作为指针传递给函数的类型。有人可以帮忙吗?

typedef struct Process 
{
int id;
int arrival;
int life;
int address[10]; //contain address space(s) of the Process
struct Process *next;
} Process_rec, *Process_ptr;

Process_ptr addProcess(Process_ptr old,int a, int b, int c, int d[10]) 
{
...
Process_ptr newProcess = (Process_ptr) malloc(sizeof(Process_rec));
newProcess->address = d;
...
}

main()
{
int address[10] = { 0 };
...
for loop
{
address[i] = something
}
p = addProcess(p, id,arrival,life,address);

我试图将构造函数中的数组更改为指针,但是,我创建的所有进程最终将具有与我创建的最后一个进程相同的数组。

如果我使用上面的代码,它应该将 main 中的数组地址 [10] 粘贴到函数,然后从函数到结构。我一直遇到错误“从类型'int *'分配给类型'int [10]'时类型不兼容”,这意味着它将函数中的数组d [10]视为指针,但我确实使用了数组而不是指针? !?

【问题讨论】:

  • C 不支持数组类型的函数参数。阅读comp.lang.c FAQ 的第 6 节。
  • @KeithThompson 我猜是这种情况并将结构中的地址更改为指针类型,但是,我最终拥有并且进程指向相同的地址,因为它都指向 main 中的地址数组.并且 main 中的地址将不断变化,直到最后一个 Process 被读取。你能建议我如何有效地复制这些值吗?我可以做一个循环,但这似乎不是正确的方法。

标签: c arrays pointers struct


【解决方案1】:

正如@Keith Thompson 所解释的,如果您定义:

Process_ptr addProcess(Process_ptr old,int a, int b, int c, int d[10])

...那么d实际上是一个指针,即完全等价于int *d

你想做的是这样的:

memcpy(newProcess->address, d, 10*sizeof(d[0]));

顺便说一句,您不需要转换malloc 的结果。见Do I cast the result of malloc?

【讨论】:

  • 谢谢!我添加了 newProcess->address = malloc(sizeof(int) * 10); memcpy(newProcess->address, d, 10*sizeof(d[0]));它按预期工作!我知道内存操作方法几乎是 C 语言中的基本内容,以后我一定会探索它们
【解决方案2】:

d同上是一个指针,核心应该是:

newProcess->address = d;

address 是一个静态数组,而不是指针。数组名表示数组的地址,不能修改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2021-11-02
    • 2019-05-03
    相关资源
    最近更新 更多