如何在c中初始化结构中数组的所有值
我需要将数组的所有值初始化为0。newCount->numbers[1]={0}给出错误“expected expression”。我该怎么办如何在c中初始化结构中数组的所有值,c,arrays,structure,C,Arrays,Structure,我需要将数组的所有值初始化为0。newCount->numbers[1]={0}给出错误“expected expression”。我该怎么办 typedef struct count *Count; struct count{ int numbers[101]; int totalCalls; int totalCallsEach[101]; }; Count create_Count(void){ Count newCount = malloc(sizeo
typedef struct count *Count;
struct count{
int numbers[101];
int totalCalls;
int totalCallsEach[101];
};
Count create_Count(void){
Count newCount = malloc(sizeof(struct count));
newCount->numbers[101] = {0};
newCount->totalCalls = 0;
return newCount;
}
使用
memset
将数组的值设置为0
memset(newCount->numbers, 0, sizeof(newCount->numbers));
memset(newCount->totalCallsEach, 0, sizeof(newCount->totalCallsEach));
PS
typedef struct count *Count;
不是好的typedef
。使用:
typedef struct count Count;
或
您可以使用
memset
()
如果在分配对象时需要将数组初始化为all-bits-0,请使用
calloc
而不是malloc
:
newCount = calloc( 1, sizeof *newCount );
这也会将totalCalls
和totalCallsEach
成员初始化为all-bits-0
如果要将所有元素设置为任何其他值而不循环,则需要使用memset
样式说明:通常,在typedef
中隐藏指针不是一个好主意。如果任何使用Count
类型的对象的人需要知道其指针的位置(即,他们需要使用->
操作符来访问成员,而不是
),那么最好执行以下操作
typedef struct count Count;
...
Count *create_count(void)
{
Count *new_count = ...;
...
}
在声明中,使对象的指针显式
如果您不希望任何人直接取消引用或访问Count
对象的成员,并提供用于设置、获取和显示成员的API,如
myCount = createNewCount();
deleteCount( myCount );
x = getTotalCalls( myCount );
addCount( myCount, value );
printf( "myCount = %s\n", formatCount( myCount ) );
等等,那么可以将指针隐藏在typedef后面 struct count*newCount=(struct count*)calloc(1,sizeof(struct count))
它不使用malloc calloc,而是创建一个“struct count”大小的内存,并将其初始化为零。看起来
count
是count*
的一种类型……因此newCount
是一个指针,OP在结构上使用了一个typedef,其中typedef创建了count作为指针,因此不需要额外的“*”。对我来说,答案中的oops只是不在结构上使用typedef的另一个原因。这如何添加任何尚未解决的内容?
typedef struct count Count;
...
Count *create_count(void)
{
Count *new_count = ...;
...
}
myCount = createNewCount();
deleteCount( myCount );
x = getTotalCalls( myCount );
addCount( myCount, value );
printf( "myCount = %s\n", formatCount( myCount ) );