gpt4 book ai didi

c - 字符串数组初始化

转载 作者:行者123 更新时间:2023-12-03 20:44:15 25 4
gpt4 key购买 nike

这段代码交换给定数组的第一个和最后一个元素:

#include <stdio.h>

/* swap first and last element of array */
void fn(void *v, size_t length, size_t size)
{
char *a = (char *)v;
char *b = (char *)v + size * (length - 1);
char temp;

do {
temp = *a;
*a++ = *b;
*b++ = temp;
} while (--size > 0);
}

int main(void)
{
int a[] = {0, 1, 2};
double b[] = {0., 1., 2.};
char c[][15] = {"Hello", ",", "this is a test"};

fn(a, 3, sizeof(a[0]));
fn(b, 3, sizeof(b[0]));
fn(c, 3, sizeof(c[0]));
printf("%d %d\n", a[0], a[2]);
printf("%f %f\n", b[0], b[2]);
printf("%s %s\n", c[0], c[2]);
return 0;
}

输出:

2 0
2.000000 0.000000
this is a test Hello

我的问题是:

代码安全吗,保证c[0]被编译器初始化为

{'h', 'e', 'l', 'l', 'o', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

c[0]可能包含{'h', 'e', 'l', 'l', 'o', 0, [garbage]}?

编辑:如果c没有初始化呢?

int main(void)
{
char c[3][15];

strcpy(c[0], "Hello");
strcpy(c[1], ",");
strcpy(c[2], "this is a test");
fn(c, 3, sizeof(c[0]));
printf("%s %s\n", c[0], c[2]);
return 0;
}

使用 fn 安全吗? (c[0] 包含 9 个字节的垃圾)

最佳答案

来自 C11 标准第 6.7.9 章:

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration

是的,c[0] 将被完全初始化。

这也是由 C99 标准(第 6.7.8/21 章)定义的。对于标准的早期版本,我不知道这一点(不再...... ;-))。

关于c - 字符串数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25489325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com