Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何初始化结构中的数组字段?_C - Fatal编程技术网

C 如何初始化结构中的数组字段?

C 如何初始化结构中的数组字段?,c,C,所以我有一个练习要求我定义一个结构,它有两个字段:一个字段存储一个已经定义大小的数组,一个字段存储数组的长度。然后我必须定义一个函数来初始化结构中的2个字段,以及另一个函数来打印这2个字段 我只是一个编程初学者,下面是我编写代码的尝试,但它似乎不起作用。提前谢谢你的帮助 #include<stdio.h> #include<string.h> #define SIZE 10 typedef struct stdata data{ int array[SIZE];

所以我有一个练习要求我定义一个结构,它有两个字段:一个字段存储一个已经定义大小的数组,一个字段存储数组的长度。然后我必须定义一个函数来初始化结构中的2个字段,以及另一个函数来打印这2个字段 我只是一个编程初学者,下面是我编写代码的尝试,但它似乎不起作用。提前谢谢你的帮助

#include<stdio.h>
#include<string.h>
#define SIZE 10
typedef struct stdata data{
    int array[SIZE];
    int length;
}
void initialize (int array[],int length){
    data p;
    p.array[SIZE]=array;
    p.length=length;
}
void print(data p){
    printf("%d %d ",p.array,p.length);
}
#包括
#包括
#定义尺寸10
类型定义结构stdata数据{
int数组[大小];
整数长度;
}
无效初始化(整数数组[],整数长度){
数据p;
p、 数组[大小]=数组;
p、 长度=长度;
}
作废打印(数据页){
printf(“%d%d”,p.array,p.length);
}

你可以用两种不同的方法来做这件事,两种方法都是正确的:

方法1:

memcpy(p.array, array, sizeof(int) * length);
方法2:(使用循环)

(inti=0;i提示:检查
p.array
..
p.array[SIZE]
的数据类型是否为1,C使用基于0的索引。此外,您不能分配数组。如何将数组分配给结构中的字段?顺便说一句,
typedef struct stdata{…}
-->
typedef struct stdata{…}data不能,必须使用循环逐个元素分配。
for (int i = 0; i < length; i++) p.array[i] = array[i];