繁体   English   中英

为什么此printf语句或缺少该语句会改变for循环的效果?

[英]Why does this printf statement, or lack there of, alter the effect of the for loop?

代码的第一部分:

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

int main(void)
{
    string name = GetString();
    int n = strlen(name);
    int j = 0;
    int c = 0;
    char initials[j];    
    char input[c];
    char space[] = {' '};

    for (int i = 0, c = 0; i < n; i++, c++)
    {        
        input[c] = name[i];

        printf("%c, %c\n", name[i], input[c]);     
    } 

问题区域:

    printf("%d\n", n);
    for (int i = 0, c = 0; i < n; i++, c++)
    {                 
        if (input[c] != space[0])
        {
            initials[j] = input[c];
            j++;
            break;
        }
        printf("loop test\n");
    }

    j = 0;

    printf("%c\n", initials[j]);      
}

如果我的输入是:

     hello

然后我的输出就是我想要的(循环测试==输入之前的空格数):

loop test
loop test
loop test
loop test
loop test
h

除非我删除:

printf("%d\n", n);

然后,如果我的输入以> = 4个空格开头,则我的输出为:

loop test
loop test
loop test
loop test
// blank line
// blank line         

这两个注释是输出中的实际空白行

*对于某些错误的printf语句,很抱歉,我正在尝试确定该错误。

一个主要问题在这里:

int c = 0;
 ...
char input[c];

input[]设为零长度数组。 然后,代码将快乐地写入超出其结尾的位置,这相当于在堆栈帧的其他部分上进行了随机写入。

解决方法是在写入数组之前适当调整数组大小。

也有

int j = 0;
 ...
char initials[j];    

您可能想要更多类似的东西:

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

int main(void)
{
  string name = GetString();
  int n = strlen(name);
  int j = 0;
  int c = 0;
  char *initials = calloc(n,1);    
  char *input = calloc(n,1);

  for (int i = 0, c = 0; i < n; i++, c++)
  {        
    input[c] = name[i];

    printf("%c, %c\n", name[i], input[c]);     
  } 

  printf("%d\n", n);
  for (int c = 0; c < n; c++) // you weren't using i in the loop
  {                 
    if (input[c] != ' ')
    {
        initials[j] = input[c];
        j++;
        break;
    }
    printf("loop test\n");
  }

  j = 0;

  printf("%c\n", initials[j]);      

  free(initials);
  free(input);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM