简体   繁体   English

C:为什么我不能在 function 里面的 malloc

[英]C: Why can't I malloc inside the function

I have int *b and a function我有int *b和 function

void to_Binary(int num, int range, int **bi_res)
{
   int k = num, c = 0, r;
   *bi_res = (int *) calloc(range,sizeof(int));

   while (range >= c) {
        r = k%2; 
        c++; 
        (*bi_res)[range-c] = r; 
        k /= 2;
    }

   return;
}

This is an example of how I send b to the function这是我如何将b发送到 function 的示例

 void main
{
   // A small example if you want to replicate. 
   int *b;
   int i = 0;
   to_Binary(56,6,&b);
   while (i < 6) {printf("%d\n",b[i]); i++;}
   return;
} 

but it gives me seg fault in the loop但它给了我循环中的段错误

Note: The function itself works fine and does what it has to do if I access it in other ways but in the case I am required I have to return an array of ints that I can't know the size of注意: function 本身工作正常,如果我以其他方式访问它,它必须做的事情,但如果我需要返回一个我不知道大小的整数数组

There are at least two problems with the while loop. while 循环至少有两个问题。 The first one is that you are using an incorrect expression in this statement第一个是您在此语句中使用了不正确的表达式

*bi_res[range-c] = r;

You have to write你必须写

( *bi_res )[range-c] = r;

The second one is that if you will even use the correct expression nevertheless when range is equal to c you will try to access beyond the allocated array due to this increment within the loop第二个是,如果您甚至使用正确的表达式,但当范围等于 c 时,您将尝试访问超出分配的数组,因为循环内的这个增量

c++;

Thus the expression因此表达式

range-c

will have a negative value.会有一个负值。

You could write the loop like你可以像这样写循环

while (range != c) {
    //...
}

And this statement而这个说法

k =/ 2;

contains a syntax error.包含语法错误。 You mean你的意思是

k /= 2;

Pay attention to that the return statement is redundant.请注意,return 语句是多余的。

And the function main should be declared like function main 应该声明为

int main( void )

and you should free the allocated memory in main.并且您应该在 main 中释放分配的 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM