2016-06-13 34 views
1

在這個節目,我已經被要求只使用指針在虛空功能如何從這項計劃中

#include <stdio.h> 
#include "power.c" 
#define SIZE 20 
int count = 0; 

void test(int *n, int *o) { 
    long long sum = 0, temp; 
    int remainder, digits = 0; 
    int i; 
    int a[SIZE]; 
    temp = *n; 
    while (temp != 0) { 
     digits++; 
     temp = temp/10; 
    } 

    temp = *n; 

    while (temp != 0) { 
     remainder = temp%10; 
     sum = sum + power(remainder, digits); 
     temp = temp/10; 
    }  

    if (*n == sum) 
    { 
     count++; 
     a[count] = *n; 
    } 
    o = a; 
    for(i=1;i<=count;i++){ 
     printf("*******%i,%d\n",i,o[i]); 
    } 
} 

,並在這裏得到每個元素的值是測試臺

#include <stdio.h> 
#define SIZE 20 
int main() { 
    int c, a, b; 
    int *x; 
    int *y;  
    int i; 
    a = 2 ; 
    b = 1000; 
    //b = 345678910; 
    for (c = a; c <= b; c++) { 
     x = &c; 
     test(x,y);  
    } 
} 

它打印出像

******* 1,2- ******* 2,3- ******* 12407

這些值是正確的,但我想在測試平臺中調用測試後打印y的每個元素,並期望這些值與上面的值相似,但我不知道該怎麼做。我正在尋求你的幫助。

問候 託尼

+0

在的函數'末端test'你設置'o = a;'就好像你希望本地(自動)數組'a []'會在'main'中發現它回到'y'。它不會,它只是覆蓋作爲參數傳遞的指針的*副本,返回的指針將被丟棄。即使你*正確地將'a []'傳回''main',那麼這個數組已經超出了範圍。 –

+0

試試'static int a [SIZE];'在你的測試函數中......' – cleblanc

+0

'for(i = 1; i <= count; i ++)'是錯誤的,數組從'0'到'size-1' ,所以'for(i = 0; i

回答

0

答案是,你不能打印值調用test後。原因是當test返回時a超出範圍。換句話說 - y根本沒有指向有效內存,任何嘗試訪問它都可能導致程序崩潰。

您有以下問題:

1)y指向時test回報(如上所述)

2)count不得全球

3)count應該開始無效的內存從零而不是一個

那看起來:

// int count = 0; Don't make it global 

void test(int *n, int *o, int* cnt) 
{ 
    .... 
    int count = 0; 
    int* a = malloc(SIZE * sizeof(int)); 
    .... 

    if (*n == sum) 
    { 
     a[count] = *n; // Switch the two statements to index from zero 
     count++; 
    } 
    o = a; 
    *cnt = count;  // Return the value of count 

    for(i=0;i<count;i++){ // Notice this change - start index from zero 
     printf("*******%i,%d\n",i,o[i]); 
    } 
} 

int main() { 
    int count; 
    .... 

    test(x, y, &count); // Pass a pointer to count 

    // Now print y 
    for(i=0; i<count; i++){ 
     printf("*******%d\n", y[i]); 
    } 
    free(y); // Release memory when done with it 

到動態存儲器分配的替代方法是聲明陣列中主要:

int main() { 
    int count; 
    int y[SIZE]; 
    .... 

    test(x, y, &count); // Pass a pointer to count 

    // Now print y 
    for(i=0; i<count; i++){ 
     printf("*******%d\n", y[i]); 
    } 

,並在功能只是使用y,而不是直接的可變a