C中的数组索引作为长整数给出了分段错误

sys*_*ult 4 c pointers segmentation-fault

以下C代码给出了分段错误:

#include <stdio.h>
#include <stdint.h>

int main(){
        uint32_t *a;
        uint32_t idx=1233245613;
        a[idx]=1233;
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何在C中使用uint32_t作为数组的索引?或者我如何使用类似数组的结构,它可以将uint32_t和12位数作为索引?

我很感激任何帮助.

Bri*_*ndy 9

  • 变量"a"只是指针可变.
  • 指针变量保存内存位置的地址.
  • 您需要将a指向一个具有您已经分配的空间的内存位置.

你也试图在数组中进行索引.您可能没有足够的可用内存,因此请务必检查是否为NULL.

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

int main(void){

        uint32_t *a;
        uint32_t idx=1233245613;

        //This allows you to index from 0 to 1233245613
        // don't try to index past that number
        a = malloc((idx+1) * sizeof *a);
        if(a == NULL)
        {
           printf("not enough memory");
           return 1;
        }


        a[idx]=1233;
        free(a);
        return 0;
}
Run Code Online (Sandbox Code Playgroud)