[英]Return array from a function using a pointer C
我试图理解指针和函数,特别是从函数返回数组时如何使用指针。 我试图编写一些代码以查看是否理解,但我显然不明白。 您能看看我告诉我我做错了吗? 谢谢。
#include <stdio.h>
int *elmntsum(int *a, int *b);
int main()
{
int *z;
int x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int y = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20} ;
z = elmntsum(x, y);
int t;
for (t = 0 ; t < 10 ;t++){
printf( "%d\n", z[t]);
}
return(0);
}
int *elmntsum(int *a, int *b){
static int *c;
int t;
for (t = 0 ; t < 10 ;t++){
c[t] = a[t] + b[t];
}
return(c);
}
您的代码有很多问题,最重要的是您没有为c
分配空间。
如果您真的不知道它为什么有用,请不要使用static
,在这种情况下它肯定是没有用的。
另一个重要的问题是x
和y
的声明,它们应声明为数组,即
int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int y[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20} ;
你可以这样
int *elmntsum(int *a, int *b, size_t count) {
int *c;
c = malloc(count * sizeof(*c));
if (c == NULL)
return NULL;
for (size_t t = 0 ; t < count ;t++)
c[t] = a[t] + b[t];
return c;
}
然后您的main()
可能看起来像这样
int main()
{
int *z;
int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int y[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20} ;
z = elmntsum(x, y, 10);
if (z == NULL)
return -1;
for (size_t t = 0 ; t < 10 ;t++){
printf("%d\n", z[t]);
}
free(z);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.