首页 文章

将数组(不是指针)传递给c中的结构

提问于
浏览
0

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

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]粘贴到函数中,然后从函数粘贴到struct . 我从类型'int *'“分配到类型'int [10]'时遇到错误”不兼容的类型,这意味着它将函数中的数组d [10]视为指针,但我确实使用数组而不是指针? !?

2 回答

  • 2

    正如@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?

  • 0

    d 是上面的指针,核心应该是:

    newProcess->address = d;

    address 是静态数组,而不是指针 . 数组名称表示要修改的数组's address, and it can' .

相关问题