返回int数组用C [英] Returning array of int in C
问题描述
我有这样的code:
1 #include <stdio.h>
2 #include <string.h>
3 #define LENGTH(a) sizeof(a)/sizeof(a[0]);
4
5 int *getNbits(int, int, char *);
6
7 int main() {
8 char ins[] = "00001111000011110000111100001111";
9 int *x = getNbits(0, 32, ins);
10
11 for (int i = 0; i < LENGTH(x) ; i++){
12
13 printf("%d", *(x + i));
14 }
15 return 0;
16 }
17
18 int* getNbits(int start, int offset, char instr[33]) {
19
20 int result[offset - 1];
21 for (int i = 0; i < offset; i++) {
22 result[i] = instr[i + start] == '1' ? 1 : 0; //- '0';
23 }
24 return result;
25 }
基本上,getNbits()获得字符数组(这是0或1的),并返回int数组,每个元素是0或1。
Basically, getNbits() gets an array of chars (which are 0's or 1's) and returns an array of ints, each element is a 0 or a 1.
如果我尝试打印阵列结果因为我在for循环创建它(用printf(%d个,结果由[i]))将返回000011110000 .....
If I try to print the array "result" as I am creating it in the for loop (using printf("%d",result[i]) ) it will return 000011110000.....
但我有返回类型的麻烦,它给了我一个警告:函数返回局部变量的地址。而循环主只打印垃圾值。
But I am having trouble with the return type, it gives me a warning: function returns address of local variable. And the for loop in main just prints garbage values.
推荐答案
的结果
变量是本地getNbits。这意味着它可以尽快释放的函数返回。
The result
variable is local to getNbits. This means it can be deallocated as soon as the function returns.
不要返回一个局部变量的地址作为指针 - 它能够而且将会释放
相反,分配整数这样的:
Instead, allocate the integers like this:
int* retVal = malloc(sizeof(int) * 10);
然后返回 retVal的
从getNbits。
看到这个网址:
http://ww2.cs.mu.oz.au /~mgiuca/253/malloc.html
请注意:如果使用的malloc
上面,还必须使用免费
来释放
分配的内存就不再需要后:
NOTE: If you use malloc
above, you must also use free
to release the
allocated memory after it is no longer needed:
/* When the array is no longer needed */
free(x);
在自由的角度来看,变量名是 X
,因为这是左值分配
从呼叫getNbits。不要叫免费
从getNbits。
At the point of the free, the variable name is x
because that was the lvalue assigned
from the call to getNbits. Don't call free
from getNbits.
这篇关于返回int数组用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!