我需要将数组的所有值初始化为0. newCount-> numbers [1] = {0}给出错误"期望表达式"。我该怎么做呢?
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;
}
答案 0 :(得分:2)
使用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;
或
typedef struct count *CountPtr;
答案 1 :(得分:2)
如果在分配对象时需要将数组初始化为all-bits-0,请使用calloc
而不是malloc
:
newCount = calloc( 1, sizeof *newCount );
这也会将totalCalls
和totalCallsEach
成员初始化为all-bits-0。
如果您想将所有元素设置为任何其他值而不循环遍历每个元素,则需要使用memset
。
样式注释:通常,在typedef
内隐藏指针并不是一个好主意。如果使用Count
类型的对象的任何人需要知道它的指针(即,他们需要使用->
运算符来访问成员而不是.
),那么它&# 39;做一些像
typedef struct count Count;
...
Count *create_count(void)
{
Count *new_count = ...;
...
}
IOW,在声明中明确指出对象的指针。
如果您不打算让任何人直接取消引用或访问Count
个对象的成员,并提供用于设置,获取和显示
myCount = createNewCount();
deleteCount( myCount );
x = getTotalCalls( myCount );
addCount( myCount, value );
printf( "myCount = %s\n", formatCount( myCount ) );
等等,然后可以隐藏typedef后面的指针。
答案 2 :(得分:1)
您可以使用memset
(doc)
memset(newCount->numbers, 0, 101*sizeof(int));
答案 3 :(得分:-1)
struct count * newCount =(struct count *)calloc(1,sizeof(struct count))
而不是malloc使用calloc,它会创建一个大小为&#34; struct count&#34;并将其初始化为零。