gpt4 book ai didi

c - 在 C 中使用函数返回数组时出现杂散错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:47 27 4
gpt4 key购买 nike

我一直在尝试使用下面的代码返回一个数组 -

#include <stdio.h>
int* factor(int num);
int main(void)
{
int num;
printf("\nEnter a number:");
scanf("%d",&num);
int* array;
array=factor(num);
for(int counter=0;counter<num;counter++)
{
printf("%d\n",array[counter]);
}
}
int* factor(int num)
{
   int NumberArray[100];
for(int i=0; i<num; i++){
NumberArray[i] = i;
}
return NumberArray;
}

这产生了以下输出-

gcc assignment3func.c -o assignment3func
assignment3func.c: In function ‘factor’:
assignment3func.c:19:1: error: stray ‘\302’ in program
   int NumberArray[100];
^
assignment3func.c:19:1: error: stray ‘\240’ in program
assignment3func.c:19:1: error: stray ‘\302’ in program
assignment3func.c:19:1: error: stray ‘\240’ in program
assignment3func.c:23:11: warning: function returns address of local variable [-Wreturn-local-addr]
return NumberArray;
^

请帮帮我。我无法理解流浪的东西。

最佳答案

该数组被声明为具有自动存储持续时间,因此当它超出范围时,它会被您的编译器释放。如果您想创建一个可以返回的数组,请使用动态内存分配它。

int* NumberArray = malloc(sizeof(int)*100);

关于c - 在 C 中使用函数返回数组时出现杂散错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46528779/

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