我一直在尝试使用下面的代码返回一个数组 -
#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);
回答关于如何在不使用 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;
}
}
在这里,您在调用函数中创建数组,并在被调用函数中传递指向它的指针。然后被调用函数对调用函数范围内的数组进行操作。
“杂散的‘�’”/“杂散的‘�’”消息是关于在您的源代码中有额外的非打印(不可见)unicode 字符。这些通常来自其他来源的复制粘贴代码。
Sprecifically,双字节序列是一个不间断空格字符的 UTF-8 编码。不幸的是,用你的编辑器删除它们可能很棘手,因为它们是不可见的!如果您可以将您的编辑器设置为 ASCII 模式而不是 UNICODE,它们可能会出现,因此您可以删除它们。