【发布时间】:2015-12-19 21:51:29
【问题描述】:
我有这个代码:
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);
谢谢
【问题讨论】:
-
@JackWilliams 他不会那样做。他的代码中的重新分配没有大小写。他说他不想那样做。
-
您很可能使用 C++ 编译器编译源代码。
void*与 C 中的int*(或任何其他数据指针)兼容。因此您不需要在 C 中进行强制转换。 -
@l3x:它不兼容(这个词在C语言中具有非常特殊的含义),但它可以通过赋值隐式转换。您可以称其为“赋值兼容”,尽管 C 标准不使用该术语。
-
请注意
ptr = realloc(ptr, new_size);是危险的,因为如果重新分配失败,您(通常)会丢失指向原始内存的指针——您只是用空指针覆盖了ptr。始终在void *new_space = realloc(ptr, new_size); if (new_space != 0) ptr = new_space;上使用变体。
标签: c