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

标签 c arrays pointers struct

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

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] 视为指针,但我确实使用数组而不是指针? !?

最佳答案

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

关于c - 将数组(不是指针)传递给 c 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29244891/

相关文章:

混淆结果 : Array of pointers in C

c - for 循环中的段错误

c++ - 将带有字符串参数的函数指针从 Swift 传递到 Obj C++

c - 从c中的命令行读取的字符串中打印转义字符

将 double 转换为整数?

python - 如何按python中两个轴的最大值对列表进行排序?

java - 在 Java 中,如何确定 char 数组是否包含特定字符?

c - 使用 CDT 类验证 C 代码

mysql - 在 Linux 中使用 MySQL "error: unknown type name ‘uint’ 编译 C 项目时出错

javascript - 从 $.getJSON 迭代集合并将新对象推送到数组中会使数组为空