c - 我希望循环复制空字符或其他内容,但它再次从头开始复制 char。这是为什么?这个循环是如何工作的?

标签 c arrays string loops

我正在尝试检查循环中的 char 数组是否从其他 char 数组复制字符,该字符数组的字符小于循环迭代次数

#include <stdio.h>[enter image description here][1]
#include <string.h>

int main()
{
    int c=0;
    char a[10],x[5]="hamme";
while(c<10)
    {
        a[c]=x[c];
    c++;
    }
    printf("%s",a);
    return 0;

}

最佳答案

x[5]="hamme"

创建 5 的字符数组字符,而不是带有 "hamme"字符串这需要 6要存储的字符(回想一下,您需要存储末尾的空字符)

循环时 while(c<10)您通过读取超过 x 的末尾(超出数组边界)来调用未定义的行为 .

您的“有时复制有时不复制——是未定义行为的结果。

如果声明char x[] = "hamme";然后 x将被初始化以包含 nul-terminating 字符,您可以简单地循环直到它被复制到 a ,例如

#include <stdio.h>

int main (void) {

    int c = 0;
    char a[10],
        x[] = "hamme";

    do
        a[c] = x[c];
    while (x[c++]);

    printf ("%s\n", a);

    return 0;
}

(注意:您必须确保 a 有足够的存储空间来保存 x 中的字符串,否则您将回到未定义行为的困境。)

为确保不会发生这种情况,您可以包含 string.h并比较 x 的长度(加上 1 )到 a[] 中可用的存储空间并且只有在足够的情况下才复制,例如

#include <stdio.h>
#include <string.h>

int main (void) {

    size_t c = 0;
    char a[10],
        x[] = "hamme";

    if (strlen (x) + 1 > sizeof a) {
        fputs ("error, length of x exceeds storage in a.\n", stderr);
        return 1;
    }

    do
        a[c] = x[c];
    while (x[c++]);

    printf ("%s\n", a);

    return 0;
}

(注意 c 的类型从 int 更改为 size_t 以避免在 if (strlen (x) + 1 > sizeof a) 中比较有符号和无符号值)

关于c - 我希望循环复制空字符或其他内容,但它再次从头开始复制 char。这是为什么?这个循环是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54706928/

相关文章:

python - pyparsing 带引号的字符串

c++ - 有没有更好的方法从字符串创建目录? cpp,创建目录,stringstream,字符串。

c++ - 数组上的 C++ for 循环

javascript - JS : Create a method to return an array that does not include the index values from the array passed to my method

javascript - 通过属性和值获取数组对象项的索引

c - 你如何为c中的数组中的元素赋值?

C - 以相同字母开头和结尾的单词

c - 给另一种类型变量的指针赋值

C:通过 UDP 发送 float 导致随机符号

c - 使用 openmp 时可能出现竞争条件问题