C语言中使用函数返回数组时的杂散错误

r3i60tvu  于 2023-04-29  发布在  其他
关注(0)|答案(3)|浏览(182)

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

#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;
           ^

请帮帮我我不明白流浪的事。

v64noz0r

v64noz0r1#

该数组是用自动存储持续时间声明的,因此当它超出范围时,编译器会释放它。如果你想创建一个可以返回的数组,用动态内存分配它。
int* NumberArray = malloc(sizeof(int)*100);

qzwqbdag

qzwqbdag2#

关于如何在不使用malloc的情况下返回数组的问题:

#include <stdio.h>
void factor(int num, int *NumberArray); //pass a pointer to an array to the function
int main(void)
{
  int num;
  printf("\nEnter a number:");
  scanf("%d",&num);
  int array[100]; //create the array in the calling function
  factor(num, array);
  for(int counter=0;counter<num;counter++)
  {
      printf("%d\n",array[counter]);
  }
}
void factor(int num, int *NumberArray)
{
   for(int i=0; i<num; i++){
       NumberArray[i] = i;
   }
}

在这里,您在调用函数中创建数组,并在被调用函数中传递指向该数组的指针。然后,被调用的函数对调用函数中作用域的数组进行操作。

o8x7eapl

o8x7eapl3#

“stray '\302'”/“stray '\240'”消息是关于在源代码中有额外的非打印(不可见)Unicode字符。这些通常来自其他源代码的复制-粘贴。
具体地说,双字节的\302\240序列是一个非中断空格字符的UTF-8编码。不幸的是,删除这些与您的编辑器可以棘手,因为他们是不可见的!如果您可以将编辑器置于ASCII模式而不是Unicode模式,则它们可能会显示出来,以便您可以删除它们。

相关问题