大家好,我的 for 循环中发生了一件非常奇怪的事情。
当我在这里执行这段代码时:
#include <stdio.h>
#include <string.h>
char* repeat(char c, int n);
int main(void)
{
char* input;
input = repeat('c', 12);
return 0;
}
char* repeat(char c, int n)
{
char* out;
for (int i = 0; i < 12; ++i) //FIX ITERATION
{
int len = strlen(out);
out[len] = c;
out[len+1] = '\0';
}
printf("%s\n", out);
return out;
}
我得到了预期的输出:
cccccccccccc
但是当我在我的方法中使用传递的 int 时,像这样:
char* repeat(char c, int n)
{
char* out;
for (int i = 0; i < n; ++i) //VARIABLE ITERATION
{
int len = strlen(out);
out[len] = c;
out[len+1] = '\0';
}
printf("%s\n", out);
return out;
}
我只是得到这个作为输出:
cccc
请告诉我我做错了什么。我不知道错误可能是什么?
感谢您的帮助!
最佳答案
这一行就是问题所在
int len = strlen(out);
out[len] = c;
out[len+1] = '\0';
out
未初始化。您没有在此语句中分配内存:
char* out;
所以你正在经历Undefined Behavior .
第 3.4.3 节
1 undefined behavior
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
第 4.1 节:
An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior. If T is a non-class type, the type of the rvalue is the cv-unqualified version of T. Otherwise, the type of the rvalue is T.
在这两个示例中,您都显示了未定义的结果。
你必须分配内存:
char * out = malloc(sizeof(char)*50); // i have used size 50 - take sufficient what you need
//initialize it
out[0] = '\0';
确保包含 stdlib.h
。
out
现在指向一个可以容纳 50 个 char
的内存块。
关于c - for 循环突然停止 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27834395/