我正在尝试计算数组中空间的存储位置。但它也总是将 0 打印为空间位置,为什么?

问题描述 投票:0回答:1
#include <stdio.h>
#include <conio.h>

void main()
{
    int a = 0, b = 0, c = 0, e[10000];
    char d[10000];
    printf("Enter text: ");
    gets(d);

    while(d[a] != '\0')
    {
        if(d[a] != ' ')
        {
            b++;
        }
        else
        {
             e[c]=a;
             c++;
        }
        
       
        

        a++;
    }

    printf("Number of characters without spaces: %d\n", b);
    for(int i=0; i<=c; i++)
       printf("Spaces : %d \n", e[i] );
    getch();

}

每次我运行程序时,如预期的那样,空格的输出结果是空格的位置,最后是空格:0。如果我从 i<=c to i 更改 for 循环中的条件

首先这段代码无法编译,因为你有太多的右括号。

其次,您尝试直接打印数组 e,这导致打印内存地址而不是实际元素。您应该遍历数组并逐一打印元素:

for (int i = 0; i < c; i++) {
  printf("%d ", e[i]);
}
c
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.