【问题标题】:Why does this printf statement, or lack there of, alter the effect of the for loop?为什么这个 printf 语句或缺少它会改变 for 循环的效果?
【发布时间】:2015-05-05 22:53:55
【问题描述】:

第一段代码:

#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         

这两个 cmets 是输出中的实际空行

*对于一些错误的 printf 语句,我很抱歉,我试图找出错误。

【问题讨论】:

  • 虽然这不是错误,但您在函数范围内有一个名为 c 的变量,然后在每个 for 循环中还有一个名为 c 的不同变量。当您想要更改或扩展代码时,这可能会让人感到困惑。我建议为变量使用更长、更具描述性的名称。
  • @user1118321 好吧,我的印象是我只是在回忆同一个变量。感谢您的建议!

标签: c cs50


【解决方案1】:

这里有一个主要问题:

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

input[] 被设为零长度数组。然后代码愉快地写到它的末尾之外,这相当于在堆栈帧的其他部分随机写入。

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

还有

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

【讨论】:

  • 如果我不知道长度,如何正确调整尺寸?
  • @Jord:有几种策略。 “老派”的方法是让它比以往任何时候都大(1000?)。另一种方法是计算它需要多大(可能是len+1?)。另一种方法是猜测一些长度,如果它变得太小,则将其扩展(这并不容易应用于此特定代码)。
  • 感谢您的回复!
  • @Jord:如何调整首字母数组的大小?你知道字符串有 N 个字符长,并且不能超过 (N+1)/2 个字符作为首字母(给定a b c,长度为 5,有 (5+1)/2 = 3 个首字母),因此您对数组的长度有一个上限(但不要忘记允许尾随空字节)。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-10-07
    • 1970-01-01
    • 2011-12-03
    • 2023-01-16
    • 1970-01-01
    • 2021-10-05
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多