我在c中遇到了scanf()的问题

发布于 2025-02-13 20:20:38 字数 360 浏览 1 评论 0原文

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

void add(int *arr, int n);

int main() {
  int arr[] = {};
  add(arr, 4);

  return 0;
}

void add(int *arr, int n){
  for (int i = 0; i < n; i++){
    printf("%d index is : ", i);
    scanf("%d\n", &arr[i+1]);
  }
}

i == 1之后,for循环无法正常工作...执行停止,然后我必须按一些字母并执行整个循环,没有值...

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

void add(int *arr, int n);

int main() {
  int arr[] = {};
  add(arr, 4);

  return 0;
}

void add(int *arr, int n){
  for (int i = 0; i < n; i++){
    printf("%d index is : ", i);
    scanf("%d\n", &arr[i+1]);
  }
}

the for loop doesn't work after the i == 1... the execution stops and then I have to press some alphabet and executes the whole for loop with no values...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我闹别瞎闹 2025-02-20 20:20:38

在C和C ++中的此声明

int arr[] = {};

无效。初始化列表不得为空。

取而代之的是,您可以在c

int arr[4] = { 0 };

int arr[] = { [3] = 0 };

函数中写入,而不是在函数中

scanf("%d\n", &arr[i+1]);
                   ^^^

写入,

scanf("%d", &arr[i]);
                  ^^^

否则将访问数组之外​​的内存。

This declaration in C and in C++

int arr[] = {};

is invalid. The initializer list shall not be empty.

Instead you could write in C

int arr[4] = { 0 };

or

int arr[] = { [3] = 0 };

And within the function instead of

scanf("%d\n", &arr[i+1]);
                   ^^^

you have to write

scanf("%d", &arr[i]);
                  ^^^

Otherwise there will be an access to memory outside the array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文