为什么在for循环中程序在完成之前关闭?为什么是我的?

时间:2018-07-11 21:12:05

标签: c

在运行函数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 个答案:

答案 0 :(得分:2)

有几点需要注意

1),您没有初始化for循环中使用的变量t。它具有垃圾值。

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;
}