伙计们我的问题很简单,但我对它背后的理论感到困惑。如果有人能澄清,那将是可爱的。
我想传递一个特定类型变量的动态数组,并且有一个函数将该类型的变量转换为另一个变量,并在以新变量的变量数组的形式返回它之前对它做更多的工作。 / p>
这是我不太实用的代码,可以向您展示我在做什么
#include <stdio.h>
//takes in unsigned char array, and returns unsigned short array
unsigned short foo( unsigned char *array, int size)
{
int i;
unsigned short *LeArray = NULL;
LeArray = (unsigned short*) malloc(size*sizeof(unsigned short));
for ( i = 0; i < size; ++i ) &LeArray[i] = (unsigned char)&array[i];
//do more stuff to that array here before returning it
return *LeArray;
}
int main()
{
int i, ArraySize;
unsigned char *before = NULL;
unsigned short *after = NULL;
ArraySize = 9;
before = (unsigned char*) malloc(ArraySize*sizeof(unsigned char));
for(i = 0; i<ArraySize; i++) before[i] = i+5; //to get some values in
for (i = 0 ; i<ArraySize; i++) printf("\npre:%d\n",before[i]);
after = foo( before, ArraySize );
for (i = 0 ; i<ArraySize; i++) printf("\npost:%d\n",after[i]);
return 0;
}
任何帮助提示提示或解释对我都有很大帮助!!非常感谢!!
答案 0 :(得分:3)
这是一个功能,所有奇怪的地方都固定在你想做的事情上:
unsigned short* foo( unsigned char *array, int size)
// notice the return type - it's a pointer
{
int i;
unsigned short *LeArray = NULL;
LeArray = (unsigned short*) malloc(size*sizeof(unsigned short));
for ( i = 0; i < size; ++i ) LeArray[i] = (unsigned short)(array[i]);
//do more stuff to that array here before returning it
return LeArray; // notice NO DEREFERENCING here
}
基本上这是您遇到的问题:
当然还有更多内容。即:
const unsigned char* array
在这种情况下,您可以执行以下操作:
void foo(const unsigned char *array, unsigned short* LeArray, int size)
{
int i;
// no malloc as the LeArray is passed-in
for ( i = 0; i < size; ++i ) LeArray[i] = (unsigned short)(array[i]);
//do more stuff to that array here before returning it
return; // void return
}
当然,假设数组是在调用函数
中预先创建的答案 1 :(得分:1)
你快到了。
但你应该返回LeArray本身(这是内存中的地址),而不是* LeArray(这是第一个元素)。
答案 2 :(得分:1)
after = foo( before, ArraySize );
- 您在此处调用函数foo
并期望返回值类型为unsigned short *
,但函数foo
返回unsigned short
值。之后,您将访问unsigned short
函数内after
变量main
的指针,这可能会导致崩溃(意外行为)。
因此,请将您的函数原型更改为unsigned short* foo( unsigned char *array, int size)
并执行return LeArray;