2017-07-31 40 views
-4

我想获得一个很长的数字,计算它有多少数字,然后取该数字的第二个数字并乘以2,然后遍历数字的其余部分2nd,然后将其添加到数组。如果你们知道我在说什么,这是从cs50设置的信用卡问题。C - 返回数组不工作

当我把它抛出回这个错误的程序:

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; 
} 
+0

这已被问了很多次,你不能从函数返回一个数组。您需要使用'malloc()'或将该数组作为参数传递给函数,如果需要,可以在函数中对其进行修改。 –

+1

您的函数被声明为返回'long',并且您尝试返回'long [nDigits]'。抛开内存问题,你为什么认为这会起作用? – ApproachingDarknessFish

+0

在'long find_2ndlast_nums(long x)'中,你明白第一个'long'是什么意思吗? –

回答

4

有两个问题在这里:

  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); 

或者,如果你能提前知道时间的阵列的最大尺寸将是什么,你可以具备的功能填充的already-分配数组。这有一个好处,就是让你的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. 
}