【问题标题】:Why does my array display does not add up? [closed]为什么我的数组显示不加起来? [关闭]
【发布时间】:2021-10-21 03:22:31
【问题描述】:

名为“stop”的变量在显示时不会累加。它应该显示“输入数组 1 然后 2...5 的数字”。

#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>

#define MAX_SIZE 1000 

void main(){
    int num[MAX_SIZE];
    printf("Input number of integers in the array: ");
    scanf("%d", &num[MAX_SIZE]);
    
    for(size_t stop=0; stop<num[MAX_SIZE]; stop++){
        printf("\nInput numbers for array %d: ", num[stop]);
        scanf("%d", &num[stop]);
        

    }
}

the picture

【问题讨论】:

  • scanf("%d", &amp;num[MAX_SIZE]); 您正试图在数组边界之外写入。总的来说,我不清楚你想在这里实现什么。在循环内部,为什么要在为元素赋值之前打印元素?
  • 您似乎正在尝试在整个运行时设置数组的大小,在这种情况下您应该使用动态内存分配与callocmalloc 并删除预处理器指令。
  • 数组不是这样工作的。

标签: c loops


【解决方案1】:

你有两个选择。

  1. 保留预处理指令:
#include <stdlib.h>
#include <stdio.h>

#define MAX_SIZE 10 

int main(){
    int num[MAX_SIZE];
    int i;
    
    for(i=0; i < MAX_SIZE; i++){
        printf("\nInput numbers for array %d: ", i);
        scanf("%d", &num[i]);
    }
    return 0;
}
  1. 或者,这很可能是您想要做的,使用动态内存分配:
#include <stdlib.h>
#include <stdio.h>

int main(){
    int *num;
    int i, maxSize;

    printf("Input number of integers in the array: ");
    scanf("%d", &maxSize);

    num = (int *)malloc(maxSize * sizeof(int)); // allocate dynamic memory
    
    for (i=0; i < maxSize; i++){
        printf("\nInput numbers for array %d: ", i);
        scanf("%d", &num[i]);
    }

    free(num); // free pointer
    return 0;
}

【讨论】:

  • 我想你的意思是malloc(MAX_SIZE * sizeof(int))。实际上,您正在为 MAX_SIZE int 指针分配足够的内存,而不是 MAX_SIZE int。
  • @Chris 你是对的
  • 在风格上,MAX_SIZE 不再是预处理器常量,我建议将其拼写为小写。您忘记了 scanfmalloc 的测试成功 - 两者都可能失败
  • 我做了第一个并且成功了。看来我只需要输入“停止”变量。您介意解释一下 malloc() 和 sizeof() 的工作原理吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
相关资源
最近更新 更多