如何解决使用 malloc 在函数中返回一个 int 数组
我正在编写一个 C 程序,它接收一个 num(十进制、十六进制或八进制)并将其转换为二进制补码形式。
该算法应该是正确的,因为我之前在其他地方使用过它,但我对如何返回 0 和 1 的整数数组感到困惑。
我的理解是我必须使用 malloc 为这个新数组分配内存空间,但我不确定如何在语法上做到这一点。
这是我目前所拥有的:
char *itob (int num,int size) {
int binary[size];
binary[size] = (int *)malloc(size);
for (int i=0; i<size; i++) {
binary[i] = 0;
}
int decimal = num;
int counter = 0;
if (decimal > -32768 && decimal < 32767) {
if (decimal < 0) {
decimal = 65536 + decimal;
}
while (decimal>0) {
binary[counter] = decimal%2;
decimal = decimal/2;
counter++;
}
}
return binary;
}
参数 num
是要转换的数字,size
是我要打印的位数。
解决方法
如果你想分配和返回一个 int
变量数组,你需要你的函数返回一个 int*
值(不是 char*
);然后,在该函数内部简单地分配一个本地 int*
指针并在您计算并分配其元素后返回该指针。
请注意,要分配的内存块的大小应该是元素数(在您的情况下为 size
参数)乘以每个元素的大小(这将为 sizeof(int)
,为您的代码)。
您可以在返回的指针上使用 []
(索引)运算符访问已分配数据中的元素,就像数组一样。
int* itob(int num,int size) // Returns an int array,not a char array
{
// int binary[size];
// binary[size] = (int*)malloc(size);
int* binary = malloc(size * sizeof(int)); // Note: Don't cast the "malloc" return!
for (int i = 0; i < size; i++) {
binary[i] = 0;
}
int decimal = num;
int counter = size - 1; // Your code will return the digits in reverse order!
if (decimal > -32768 && decimal < 32767) {
if (decimal < 0) {
decimal = 65536 + decimal;
}
while (decimal > 0) {
binary[counter] = decimal % 2;
decimal = decimal / 2;
counter--; // See the comment on the initialization of "counter"
}
}
return binary;
}
不要忘记通过在 free()
返回的指针上调用 itob
来释放分配的内存(在调用模块中)(在您完成它之后)。
关于 malloc
返回(在 C 中)的转换(或不转换),请参阅:Do I cast the result of malloc?。
关于:
int binary[size];
binary[size] = (int *)malloc(size);
这会分配 size
字节,这对您不起作用。建议:
int *binary = malloc( size * sizeof( int ) );
if( ! binary )
{
perror( "malloc failed" );
exit( EXIT_FAILURE );
}
没有从 malloc()
转换返回值,因为在 C 中,返回类型是 void*
,它可以分配给任何指针,并且 binary[size]
是一个数组,而不是一个指针。 IE。除了不需要之外,演员阵容也是错误的
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。