[英]Error returning 2d array from a function in c
我需要帮助,请; 这是示例代码:
#include <stdio.h>
const int n = 4;
const int m = 4;
void display(int arr[n][m]){
for(int i=0; i<n; i++) {
for(int j=0;j<m;j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int *constrast(int arr[n][m])
{
int temp[n][m];
int max = 25;
int min = 10;
int uBound = 255;
int lBound = 0;
for(int i=0; i<n; i++) {
for(int j=0;j<m;j++) {
temp[i][j] = ((arr[i][j] - max) *((int)(uBound-lBound)/(max-min))+uBound;
}
}
return temp;
}
int main()
{
int disp[4][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17},
{18, 19, 20, 21},
{22, 23, 24, 25}
};
printf("Image Before Stretching:\n");
display(disp);
printf("Image After Stretching:\n");
display(constrast(disp));
return 0;
}
这是我尝试编译后收到的错误消息:
contrast.c: In function ‘display’:
contrast.c:6:4: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int i=0; i<n; i++) {
^
contrast.c:6:4: note: use option -std=c99 or -std=gnu99 to compile your code
contrast.c:7:7: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int j=0;j<m;j++) {
^
contrast.c: In function ‘constrast’:
contrast.c:21:4: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int i=0; i<n; i++) {
^
contrast.c:22:7: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int j=0;j<m;j++) {
^
contrast.c:23:82: error: expected ‘)’ before ‘;’ token
temp[i][j] = ((arr[i][j] - max) *((int)(uBound-lBound)/(max-min))+uBound;
^
contrast.c:24:7: error: expected ‘;’ before ‘}’ token
}
^
contrast.c:28:4: warning: return from incompatible pointer type [enabled by default]
return temp;
^
contrast.c:28:4: warning: function returns address of local variable [-Wreturn-local-addr]
contrast.c: In function ‘main’:
contrast.c:44:1: warning: passing argument 1 of ‘display’ from incompatible pointer type [enabled by default]
display(constrast(disp));
^
contrast.c:4:6: note: expected ‘int (*)[(sizetype)m]’ but argument is of type ‘int *’
void display(int arr[n][m]){
^
int *constrast(int arr[n][m]) { int temp[n][m]; int max = 25; int min = 10; int uBound = 255; int lBound = 0; for(int i=0; i<n; i++) { for(int j=0;j<m;j++) { temp[i][j] = ((arr[i][j] - max) *((int)(uBound-lBound)/(max-min))+uBound; } } return temp; }
除了int[4][4]
的temp
类型与int *
的函数类型不匹配之外,您将永远不会返回局部变量的地址,因为当函数结束时这些变量已经消失并且指向它的指针获胜不再有效。
您不能从 C 中的函数返回数组。解决方法是将数组包装在struct
或动态分配内存。 更好的是:将输出数组作为参数传递。
当您尝试执行 row return temp;
,它只返回指向数组的指针,然后退出函数。 但是当您的代码进入int *constrast(int arr[n][m])
函数时,该数组已在系统堆栈中分配。 返回时,它会删除该变量,而您正在尝试使用错误的指针。
作为解决方案,您也可以将结果数组指针作为参数传递,或使用全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.