c - 在c中使用指针创建数组

标签 c segmentation-fault

我是 c 语言的新手,我正在尝试编写一个使用指针创建数组的程序,

#include <stdio.h>
int main()
{
  int *i;
  scanf("%d",i);i++;
  while(1){
    scanf("%d",i);
    if(*i==*(i-1)){
     break;}
    printf("%d\n",*i);
    i++;
  }
 return 0;
}

我不断收到此错误

Command failed: ./a.out Segmentation fault

最佳答案

我认为您想要创建一个数组并向其中读取数据,然后使用指针动态显示它。

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

int main()
{
    int *A, n;

    printf("\n Enter the size of array : "); // Reading the size of array
    scanf("%d",&n);

    A = (int*) malloc(sizeof(int) * n); // Allocating memory for array 

    int i = 0;

    for(i = 0; i < n; i++) // Reading data to array
        scanf("%d", (A+i));

    // Operations on array

    for(i = 0; i < n; i++) // Printing array
        printf("%d ", A[i]);
    return 0;
}

希望这有帮助。!!

关于c - 在c中使用指针创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503701/

相关文章:

c++ - 为什么不能给指针赋值?

firefox - 在 XPCOM 组件(Firefox 扩展)中使用套接字 (nsIServerSocket)(套接字 + 新窗口 = seg 错误)

c - 二叉树双序遍历

c - 如何使单个 "makefile"创建 3 个输出二进制文件

C# 无法在未损坏的 C++ 库上找到入口点

C++ 和 MySql++::段错误?

c - 将 alignas() 应用于 C 中的整个结构

c - scanf 中的 %d 不工作。号码 4223092 出现

c - 如果 block 的大小不是 4 的倍数,为什么 efence 无法检测到越界

c++ - 为什么我在第一个代码中出现段错误,但在第二个代码中却没有?