![](/img/trans.png)
[英]C program: when I use malloc function, I find that there are always more bytes than size of the array
[英]C program displaying more characters than array size
我编写了一个小程序来连接最多 300 个字符的字符串“20746865”。 程序如下:
#include<stdio.h>
#include<string.h>
void main()
{
char test[] = {'2','0','7','4','6','8','6','5'};
char crib[300];
int i, length = 0;
while(length <= 299)
{
for(i=0; i<8;i++)
{
crib[length] = test[i];
i=i%8;
length++;
}
}
crib[length]='\0';
printf("%s", crib);
}
以下是输出:
2074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865
但是,当我计算输出中的字符数时,它显示 304 个字符。 有人能帮我理解如果数组大小只有 300,它如何打印 304 个字符吗?
您的代码中的错误是即使写入的索引超出范围,内部循环也会继续,这会导致它继续直到下一个 8 的倍数生成未定义的行为。
与之前的回复不同,此版本使用C99根据您的描述编译和工作,最大限度地减少了副本和迭代次数。
#include <stdio.h>
#include <string.h>
static const size_t OUTPUT_SIZE = 300U;
static const char INPUT[] = {'2','0','7','4','6','8','6','5'};
static const size_t INPUT_SIZE = sizeof(INPUT);
int main()
{
char output[OUTPUT_SIZE + 1];
const size_t numIter = OUTPUT_SIZE / INPUT_SIZE;
size_t idx = 0;
// copy full chunks
for (; idx < numIter; idx++)
{
memcpy(output + idx * INPUT_SIZE, INPUT, INPUT_SIZE);
}
// write the remainder
memcpy(output + numIter * INPUT_SIZE, INPUT, OUTPUT_SIZE % INPUT_SIZE);
// add null terminator
output[OUTPUT_SIZE] = '\0';
printf("result: %s\nlength: %d\n", output, strlen(output));
return 0;
}
我希望这有帮助。
你在这里有未定义的行为。 您将crib
定义为char[300]
类型,但是当您编写crib[length] = '\\0'
时,您将其索引到位置300
。 所以不清楚你的字符串实际上是空终止的。
您没有做任何规定来查看for
循环是否会超出阈值的长度,而是每 8 个字符检查一次while
循环以查看它是否已经足够长/太长。 因此,在 38 个完整的外部循环之后,它正好命中 304 个字符并终止,因为 304 不是 <= 299。
您可能应该做的是完全避免有两个循环。 相反,保留一个循环索引和基于此计算的滚动索引。 未经测试:
#include<stdio.h>
#include<string.h>
void main() {
char test[] = {'2','0','7','4','6','8','6','5'};
char crib[301];
for (int i = 0, j = 0; i < 300; i++, j = i % 8) {
crib[i] = test[j];
}
crib[length]='\0';
printf("%s", crib);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.