让我们说你有一个像这样的阵列
{ 1 2 5 7 2 3 7 4 2 1 }
Run Code Online (Sandbox Code Playgroud)
并且你想存储数组的前半部分和后半部分之间的差异在位置2和4.
诀窍是,我需要稍后在其他代码中使用这些存储的数字,所以我无法弄清楚我将如何存储这些数字.
我有这个方法
int * getPositions(int *array, int size){
int * c[(size/2)];
int counter = 0;
for(int i = 0; i < size /2; i++) {
if (*(array + i) != *(array + (size - 1) - i)) {
c[counter]= (int *) i;
counter++;
}
}return (int *) c;
}
Run Code Online (Sandbox Code Playgroud)
但它似乎存储-1774298560在每个位置.当我尝试打印它时,我知道原因
int c = (int) getPositions(array, size_of_array);
for(int i = 0; i < ((size_of_array/2)); i++){
printf("%d\t", c);
}
Run Code Online (Sandbox Code Playgroud)
所有打印出来的都是
-1774298560 -1774298560 -1774298560 -1774298560 -1774298560
Run Code Online (Sandbox Code Playgroud)
PS:我有array和size_of_array别的地方初始化.
PS:我已经考虑了这些意见并将代码更改为以下内容
int * getPositions(int *array, int size){
int * c = (int *) malloc((size_t) (size/2));
int counter = 0;
for(int i = 0; i < size /2; i++) {
if (*(array + i) != *(array + (size - 1) - i)) {
c[counter]= i;
counter++;
}
}
Run Code Online (Sandbox Code Playgroud)
如果函数应返回一个简单int数组,则需要声明一个指向int的指针,然后调用malloc为数组保留空间.然后填入数组,并返回指针.调用函数free在某些时候需要内存.
int *getPositions(int *array, int size)
{
int *c = malloc( (size/2) * sizeof(int) );
if ( c == NULL )
return NULL;
// put stuff in the array using array syntax, e.g.
c[0] = array[0];
return c;
}
Run Code Online (Sandbox Code Playgroud)
像这样调用函数
int *c = getPositions( array, size );
if ( c != NULL )
for( int i = 0; i < (size/2)); i++ )
printf( "%d\t", c[i] );
free( c );
Run Code Online (Sandbox Code Playgroud)
笔记:
NULL指针是合法的free.