我正在尝试获取一个很长的数字,计算它有多少位数字,然后取该数字的倒数第二位数字并将其乘以2,然后迭代该数字的其余部分,乘以每个第二位,然后将其添加到数组。如果你们知道我在说什么的话,这就是 cs50 中设置的信用卡问题。
当我编写程序时,它会返回此错误:
error: format specifies type 'long' but the argument has type '<dependent type>' [-Werror,-Wformat]
credit.c:22:21: error: use of undeclared identifier 'array'
printf("%ld\n", array);
^
credit.c:40:8: error: incompatible pointer to integer conversion returning 'long [nDigits]' from a function with result type 'long' [-Werror,-Wint-conversion]
return array;
^~~~~
3 errors generated.
make: *** [credit] Error 1
代码:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
long find_2ndlast_nums(long x);
int main(void)
{
long n;
long nDigits;
do
{
n = get_long_long("Please enter your credit card number:\n");
nDigits = floor(log10(labs(n))) + 1;
}
while (nDigits < 13 || nDigits > 16);
find_2ndlast_nums(n);
printf("%ld\n", array);
}
long find_2ndlast_nums(long x)
{
long nDigits = floor(log10(labs(x))) + 1;
long array[nDigits];
for (int y = 1; y < nDigits; y += 2)
{
x = (fmod((floor(x / 10 ^ y)), 10)) * 2;
array[nDigits - y] = x;
}
return array;
}
最佳答案
这里有两个问题:
当您在 C 中声明类型为 [count] 的数组时,它会在堆栈上分配。一旦函数返回,当前堆栈帧上的所有内容都将变得无效,因此您不能像这样返回堆栈分配的数组。
即使您可以返回该数组,您也将函数声明为返回 long,而不是指向 long 的指针,因此签名不正确。
我要做的是使用 malloc 为堆上的数组分配内存。将函数声明为返回指针,然后将指针返回到数组。不幸的是,调用函数必须记住随后释放指针,否则会出现内存泄漏,但这只是使用 C 时与领域相关的事情之一。
所以,像这样:
long *myFunc() {
long *array = malloc(count * sizeof(long));
// populate the array
return array;
}
在客户端:
long *array = myFunc();
// do something with array, and when you're done:
free(array);
或者,如果您可以提前知道数组的最大大小是多少,则可以让该函数填充已分配的数组。这样做的优点是让 malloc 和 free 发生在同一范围内,从而使代码更清晰。另外,如果数组不需要离开调用函数,调用函数可以在堆栈上分配数组并将其传入,从而完全不需要 malloc 和 free。
void populateArray(long *array, size_t arraySize) {
// populate array. Don't write more than arraySize objects
// or you'll cause a buffer overflow.
}
关于C - 返回数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45407272/