c - 无法分配动态内存段错误

标签 c arrays pointers dynamic malloc

我正在尝试使用函数为数组分配内存。 我已经通过引用传递指针(使用双指针)。代码编译但在运行时抛出段错误。

#include<stdio.h>
#include<stdlib.h>
//funct to read array 

int read(int **v){
    int n,ele;
    printf("enter number of elements \n");
    scanf("%d",&n);
    //p=(int*)malloc(n*(sizeof(int));
        *v= (int*)malloc(n * sizeof(int)); 
    for(int i=0;i<n;i++)
    {
        //printf("enter %d th element \n",i);
        scanf("%d",&ele);
        *v[i]=ele;
    }
    return n;
}


void main()
{
    int *p=NULL;
    int sz=read(&p);
    for(int i =0;i<5;i++)
    {
        printf("%d",p[i]);
    }
}

最佳答案

这是错误:*v[i]=ele;。在本例中,您首先为数组下标,然后取消引用它。 https://en.cppreference.com/w/c/language/operator_precedence .将其更改为 (*v)[i]=ele; 即可。

UPD。不要忘记 free(p) 以避免内存泄漏。

关于c - 无法分配动态内存段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57915279/

相关文章:

c - 使用 & 运算符和不使用 & 运算符的地址有什么区别?

c++ - 使用位域输出结构大小

c - 程序因不明原因崩溃?

我可以在 Linux 中使用 winnt.h 吗?

c++ - for 循环在 if 条件下

c - 乘法和减法的数组比较

c - 无法在 C 中使用 qsort 对 dirent 进行排序

ios - 数组 Swift 中的求和级数

c - C 中带有指针的可变大小数组/类似数组?

c - 在 C 中对数组进行排序