我有这个代码:
int * generate_code(int *bits, int Fs, int size, int *signal_size, float frameRate) { int sign_prev, i; int bit, t, j=0; int *x; float F0, N, t0, prev_i, F1; int temp = 0, temp1, temp2; F0 = frameRate * BITS_PER_FRAME; // Frequency of a train of '0's = 2.4kHz F1 = 2*F0; // Frequency of a train of '1's = 4.8kHz N = 2*(float)Fs/F1; // number of samples in one bit sign_prev = -1; prev_i = 0; x = (int *)malloc(sizeof(int)); for( i = 0 ; i < size ; i++) { t0 = (i + 1)*N; bit = bits[i]; if( bit == 1 ) { temp1 = (int)round(t0-N/2)-(int)round(prev_i+1)+1; temp2 = (int)round(t0)-(int)round(t0-N/2+1)+1; temp =j + temp1 + temp2; //printf("%d\n", (int)temp); x = realloc(x, sizeof(int)*temp); // 1 for(t=(int)round(prev_i+1); t<=(int)round(t0-N/2); t++) { *(x + j) = -sign_prev; j++; } prev_i = t0-N/2; for(t=(int)round(prev_i+1); t <= (int)round(t0); t++) { *(x + j) = sign_prev; j++; } } else { // '0' has single transition and changes sign temp =j + (int)round(t0)-(int)round(prev_i); //printf("%d\n",(int)temp); x = realloc(x, sizeof(int)*(int)temp); // 2 for(t=(int)round(prev_i); t < (int)round(t0); t++) { *(x + j) = -sign_prev; j++; } sign_prev = -sign_prev; } prev_i = t0; } *signal_size = j; return x; }
这两个realloc
线,标有//1
和//2
上一码,给我这个错误信息:
从不兼容的类型void*分配给int*
因为我不希望这段代码表现得格外奇怪或者让我崩溃,显然,我会问:如果我只是int *
通过做什么来表达它,我将来会遇到一些问题
x = (int*)realloc(x, sizeof(int)*(int)temp);
谢谢
在C中,类型的值void*
(例如返回的值realloc
)可以分配给类型的变量int*
或任何其他对象指针类型.该值是隐式转换的.
对错误消息最可能的解释是您将代码编译为C++而不是C.确保源文件名以或.c
不结束,并确保编译器配置为C编译而不是C++编译..C
.cpp
(在C++中转换结果realloc
或被malloc
认为是不好的样式.在C++中,强制转换是必要的,但你通常不会在C++中使用realloc
或malloc
首先使用.)