gpt4 book ai didi

c - 使用指针 C 从函数返回数组

转载 作者:行者123 更新时间:2023-11-30 17:08:58 25 4
gpt4 key购买 nike

我试图理解指针和函数,特别是在从函数返回数组时如何使用指针。我尝试编写一些代码来看看我是否理解它,但我显然不明白。你能看一下并告诉我我做错了什么吗?谢谢。

#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为什么有用,就不要使用它,在这种情况下它肯定没有用。

另一个重要的问题是xy的声明,它们应该声明为数组,即

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;
}

关于c - 使用指针 C 从函数返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33457293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com