Program crash after trying to access and write to structure member

蹲街弑〆低调 提交于 2019-12-25 17:43:14

问题


Working in Visual Studio in C and trying to do fft of some samples. When I attempt writing some value to member of struct my program crash and I get error access violation writing location 0x00000000.

First, I tried to use this C code, but got errors:

kiss_fft_cpx *cx_in = new kiss_fft_cpx[nfft];  
kiss_fft_cpx *cx_out = new kiss_fft_cpx[nfft]; 

in this two lines. Okay there is no new in C. I tried to modify it but I can not do it. I tried

kiss_fft_cpx *cx_in[1024];
kiss_fft_cpx *cx_out[1024];

and few lines after i tried to pass some value with

cx_in[brojac]->r = i; // this is where program breaks
cx_in[brojac]->i = q;   

from kiss_fft.h header file

typedef struct {
   kiss_fft_scalar r;
   kiss_fft_scalar i;
} kiss_fft_cpx;

typedef struct kiss_fft_state* kiss_f;

//beginning of main 
kiss_fft_cpx *cx_in[1024];
kiss_fft_cpx *cx_out[1024];

//after doing some sampling 
cx_in[brojac]->r = i; // this is where program crash
cx_in[brojac]->i = q;

回答1:


cx_in and cx_out are just pointers to an array of structs. You need to allocate the memory.

kiss_fft_cpx *cx_in = malloc(1024*sizeof(kiss_fft_cpx));
kiss_fft_cpx *cx_out = malloc(1024*sizeof(kiss_fft_cpx)); 



回答2:


kiss_fft_cpx *cx_in = new kiss_fft_cpx[nfft];  

In C++ this will allocate an array of structs. The analogous part in C is

struct kiss_fft_cpx *cx_in = malloc(nfft * sizeof(struct kiss_fft_cpx));  

You can use this as

cx_in[brojac].r = i;  // where 0 <= brojac < nfft


来源:https://stackoverflow.com/questions/57708683/program-crash-after-trying-to-access-and-write-to-structure-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!