2017-07-31 41 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. 
}