嗨,我是C语言的新手,我有一个问题:我想通过指针把一个二维数组发送给一个函数。该函数应返回指向二维数组的指针。为此,我编写了以下代码:
#include<stdio.h>
int* put(int *b);
int main()
{
int a[2][3],i,j;
system("clear");
put(a);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\na[%d][%d]= %d",i,j,a[i][j]);
}
}
return 0;
}
int* put(int *b)
{
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=i;
}
}
return b;
}当我使用gcc2de.c编译它时,它显示以下错误:
2de.c: In function ‘main’:
2de.c:9: warning: passing argument 1 of ‘put’ from incompatible pointer type
2de.c:3: note: expected ‘int *’ but argument is of type ‘int (*)[3]’
2de.c: In function ‘put’:
2de.c:28: error: subscripted value is neither array nor pointer
2de.c: In function ‘main’:
2de.c:32: error: expected declaration or statement at end of input然后我只需修改下面的函数代码:
#include<stdio.h>
int* put(int **b);
int main()
{
int a[2][3],i,j;
system("clear");
put(a);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\na[%d][%d]= %d",i,j,a[i][j]);
}
}
return 0;
}
int* put(int **b)
{
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=i;
}
}
return b;
}当我编译它时,我得到了以下错误:
2de.c: In function ‘main’:
2de.c:9: warning: passing argument 1 of ‘put’ from incompatible pointer type
2de.c:3: note: expected ‘int **’ but argument is of type ‘int (*)[3]’
2de.c: In function ‘put’:
2de.c:31: warning: return from incompatible pointer type
2de.c: In function ‘main’:
2de.c:32: error: expected declaration or statement at end of input
2de.c: In function ‘main’:
2de.c:9: warning: passing argument 1 of ‘put’ from incompatible pointer type
2de.c:3: note: expected ‘int **’ but argument is of type ‘int (*)[3]’
2de.c: In function ‘put’:
2de.c:31: warning: return from incompatible pointer type
2de.c: In function ‘main’:
2de.c:32: error: expected declaration or statement at end of input我哪里做错了?谁能告诉我通过指向函数的指针传递2d数组的方法是什么?有人能告诉我如何在函数中通过指针返回两个d数组吗?
发布于 2011-05-02 16:04:34
您遇到的第一个错误是您没有传递函数声明的正确类型。因此,为了用最少的改正量来清理代码,它可能看起来像这样:
#include<stdio.h>
void put(int *b);
int main()
{
int a[2][3],i,j;
put(&a[0][0]);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\na[%d][%d]= %d", i, j, a[i][j]);
}
}
printf("\n\n");
system("PAUSE"); // Not recommended, but works for now
return 0;
}
void put(int *b)
{
int count = 1;
int i, j;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
//b[i][j]=i;
*(b + ((i*3) + j)) = count++;
}
}
}两个主要的修正是:
还要注意,由于您传入了一个指针,因此您将修改该地址位置的值。因此,根本不需要返回指针。
希望能有所帮助。干杯!
发布于 2011-05-02 15:50:28
您将put的返回值存储在哪里?
声明应该是int** put( int **)根据您的代码。
发布于 2011-05-02 15:50:56
您遇到的第一个错误是您试图在另一个函数中定义一个函数。最简单的做法是在声明put的地方定义它:
int put()
{
/* definition of put */
}
int main()
{
/* body calls put */
}第二个问题是,在这两个代码片段中,都没有向put传递兼容的参数。
如果你想把a传递给一个函数,那么你应该注意到作为参数的数组总是衰减成指向它们的第一个元素的指针。
a的类型为int [2][3],即3个ints的2个数组的数组。这将衰减为指向3个ints或int (*)[3]的数组的指针。这应该可以解释你得到的编译错误。您应该将put声明为:
void put(int (*b)[3]);或者完全等同于:
void put(int b[][3]);因为您不能通过值传递数组,所以编译器会自动将接受数组参数的函数声明转换为接受等效指针参数的声明。
我已将返回类型更改为void,因为您在通过指针传递参数时不使用或不需要返回值。您应该从put的定义中删除return b;。
提示:不要将int[2][3]看作是一个二维数组,而是一个由数组组成的数组。
https://stackoverflow.com/questions/5854632
复制相似问题