gpt4 book ai didi

c - 声明后在 C 中使用初始化列表

转载 作者:太空宇宙 更新时间:2023-11-04 03:26:58 25 4
gpt4 key购买 nike

我正在学习 C,有些事情让我感到困惑,我读过的书并没有真正帮助澄清我遇到的问题。

所以这是我的代码:

#include <stdio.h>
#include <stdlib.h>

#define ARRAY_SIZE 5

// gcc -std=c99 stackoverflow-example.c

int main () {

// declare variable array1
int array1[ARRAY_SIZE];
// declare and init variable array2
int array2[ARRAY_SIZE] = {}; // for integers, the default value is 0

// not initialized
for (int i = 0; i < ARRAY_SIZE; i++) {
// can be anything, not guaranteed to be 0
printf("array1[%d]: %d\n", i, array1[i]);
}

// initialized with initialization list
for (int i = 0; i < ARRAY_SIZE; i++) {
// element == 0
printf("array2[%d]: %d\n", i, array2[i]);
}

// This is the part that confuses me.
// array1 = {}; // error: expected expression before ‘{’ token
// array1[] = {}; // same error

return EXIT_SUCCESS;
}

有没有方便的方法在声明后初始化这个数组?或者设置 array1 中每个元素的唯一方法是使用 for 循环,例如:

for (int i = 0; i < ARRAY_SIZE; i++)
array1[i] = 0;

// initialized with a for loop
for (int i = 0; i < ARRAY_SIZE; i++)
// now it's guaranteed to be 0
printf("array1[%d]: %d\n", i, array1[i]);

非常感谢您的帮助。我知道这是一个菜鸟问题,但它是在我尝试更熟悉 C 语言并尝试一些非书本示例代码时出现的。

如果您怀疑可能有一些我没有理解的基本知识,请告诉我,我会仔细阅读。

最佳答案

从技术上讲,initialization只能在声明时完成一次,之后的任何值存储都是赋值或复制。

大括号括起来的初始化列表只能在声明时用于数组的初始化。

对于数组的单个元素(标量项),规则是:(引用 C11,第 6.7.9 章)

The initializer for a scalar shall be a single expression, optionally enclosed in braces.

并且空列表 {} 不是标量的有效初始值设定项(表达式)。因此你得到了错误。

因此,对于已经定义的数组,重新设置也必须完成

  • 逐个成员,通过循环
  • 使用memcpy() , 或 memset如果允许的话。

关于c - 声明后在 C 中使用初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40345875/

25 4 0
文章推荐: python - 如何绘制多个列表的直方图?
文章推荐: javascript - 在 `
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com