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

标签 c arrays function

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

#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/

相关文章:

php - 获取函数声明开始的文件名和行号

c - #define LOG_MSG(...) 用于调试

c - 杀死使用clone()创建的子进程

c - 图像数据如何/为什么存储为 char - OpenCV

c++ - 将 C++/C 中的二维数组拆分为子数组

php - 如何遍历并访问多维和关联数组中的各种元素? PHP,JSON 或 XML

php - 如何在 PHP 中代理可变参数函数

c - 如何使用 3 个系数求解 C 中的二次方程?

c# - 如何返回 C# 对象而不是数组 JSON

function - 初级产业部。在函数中运行 mpi