Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.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_Arrays_Structure - Fatal编程技术网

如何在c中初始化结构中数组的所有值

如何在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

我需要将数组的所有值初始化为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(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 ) );