程序在函数 mush 中的 for 循环运行后停止。代码在 minGW 中编译没有错误。运行时,程序永远不会打印“仍在运行”。这怎么可能? mush 的目的是删除字符串 1 中与字符串 2 匹配的字符。
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
void mush(char s1[],char s2[]) {
char temp[MAXLINE];
int i, t;
copy(temp, s1);
printf("String One: %sString Temp: %s" , s1, temp);
printf("Temp Before: %s", temp);
for (i = 0; (s1[i] != '\0') && (s1[i] != '\n'); i++) {
if (s1[i] == s2[i]) {printf("s1 = s2");}
temp[t++] = s1[i];
printf("loop:");
}
printf("Still running");
copy(s1, temp);
}
最佳答案
有几点需要注意
1 ) 您没有初始化 for 循环中使用的变量 t
。它具有垃圾值(value)。
2) t
的增量不依赖于任何条件,因此最好将其移至 for 循环的增量部分
下面是代码的工作副本,并对样式进行了一些修改
#include <stdio.h>
#define MAXLINE 1000
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
void mush(char s1[],char s2[]) {
char temp[MAXLINE];
int i, t;
copy(temp, s1);
printf("String One: %s\nString Temp: %s\n" , s1, temp);
printf("Temp Before: %s\n", temp);
for (i = 0, t = 0; (s1[i] != '\0') && (s1[i] != '\n'); i++, t++) {
if (s1[i] == s2[i]) {printf("s1 = s2 (%c %c)\n", s1[i], s2[i]);}
temp[t] = s1[i];
printf("loop:\n");
}
printf("Still running\n");
copy(s1, temp);
}
int main(void) {
char s1[]="this is a test";
char s2[60];
mush(s1,s2);
return 0;
}
关于c - 为什么程序在 for 循环期间会在完成之前关闭?为什么我的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51294223/