我一直在尝试传递我的数组地址以在 main 函数中打印数组值。但它不起作用,因为它给出“X.exe 计数已停止工作”。它还显示一条警告消息,上面写着“函数正在返回局部变量的地址”。我找不到问题。如果有人发现下面给出的我的代码的指针相关问题,那将会很有帮助。
#include<stdio.h>
int * countBy(int x, int n)
{
int arr[n];
int count = x;
for(int i = 0; i < n; i++)
{
arr[i] = count;
count = count + x;
}
return arr;
}
int main()
{
int x = 2, n = 10;
int * prr;
prr = countBy(x, n);
for(int i = 0; i < 10; i++)
{
printf("%d ", prr[i]);
}
return 0;
}
最佳答案
您不能在 C 中返回数组。您需要在主函数中创建数组并将其传递给函数或使用动态分配。
传递一个输出数组:
void countBy(int x, int n, int *arr)
{
int count = x;
for(int i = 0; i < n; i++) {
arr[i] = count;
count = count + x;
}
}
int main(void)
{
int x = 2, n = 10;
int arr[n];
countBy(x, n, arr);
}
动态分配:
int * countBy(int x, int n)
{
int *arr = malloc(n * sizeof(*arr));
int count = x;
for(int i = 0; i < n; i++) {
arr[i] = count;
count = count + x;
}
return arr;
}
int main(void)
{
int x = 2, n = 10;
int *prr;
prr = countBy(x, n);
free(prr); // Remember to use free to not cause memory leaks
}
关于c - 无法将数组从另一个函数返回到主函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57937386/