C - 返回数组不起作用

标签 c arrays cs50

我正在尝试获取一个很长的数字,计算它有多少位数字,然后取该数字的倒数第二位数字并将其乘以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;
}

最佳答案

这里有两个问题:

  1. 当您在 C 中声明类型为 [count] 的数组时,它会在堆栈上分配。一旦函数返回,当前堆栈帧上的所有内容都将变得无效,因此您不能像这样返回堆栈分配的数组。

  2. 即使您可以返回该数组,您也将函数声明为返回 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/

相关文章:

c - 循环遍历 c 中预先存在的变量集的策略

c - malloc 二维数组导致 EXC_BAD_ACCESS

c# - 包含数组的结构体的大小

javascript - 提取数组的键 - 没有重复项

c - Valgrind新手,似乎不能让它开心

C - 在 Mac OSX Lion 上编译时架构 x86_64 的 undefined symbol

c - 为什么有人会用未使用的参数/参数定义 C 宏?

c - 如何检查是否从 C 程序设置了环境变量

javascript - 使用angular 4删除对象数组中的重复项

python - CS50 Web 编程 - 导入 books.csv 文件时出现 Postgres SQL 错误