0

我的代碼「兼容的指針類型」 編譯用C

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 

void getData(short int *number, char *string) 
{ 
    printf("\nPlease enter a number greater than zero: "); 
    scanf("%hd", number); 

    printf("Please enter a character string: "); 
    scanf("%s", string); 
} 

void echoPair(short int *number, char *string) 
{ 
    printf("Number: %hd Character(s): %s\n", *number, string); 
} 

int main() 
{ 
    short int *number = 0; 
    char string[32] = {0}; 

    printf("This program will ask you to enter a number greater than zero and \na character string with less than 32 characters \ninput."); 

    getData(&number, &string); 
    echoPair(&number, &string); 
    return(0); 
} 

的代碼工作正常,但我收到這些編譯器警告

warning: passing argument 1 of ‘getData’ from incompatible pointer type 
warning: passing argument 2 of ‘getData’ from incompatible pointer type 
warning: passing argument 1 of ‘echoPair’ from incompatible pointer type 
warning: passing argument 2 of ‘echoPair’ from incompatible pointer type 

如果做到這一點

getData(number, string); 
    echoPair(number, string); 

的警告走開,但在我輸入getData函數中的第一個數字後,程序得到「分段錯誤:11」。

任何人都知道如何刪除警告並保持程序正常工作?

感謝

回答

5

這裏有很多問題。


首先,該行:

short int *number = 0; 

應該是:

short int number = 0; 

因爲你使用前者,它給了你一個空指針short。這是而不是你想要什麼,因爲該野獸的第一個解除引用可能會導致你的代碼崩潰(或者,更糟的是,不是會導致你的代碼崩潰,但會導致奇怪的行爲)。


其次,你不需要在字符串的地址通過,它們將自動衰減到一個地址,所以更改:

getData (&number, &string); 
echoPair (&number, &string); 

到:

getData (&number, string); 
echoPair (&number, string); // but see last point below. 

最後,你不需要通過地址只是爲了打印它,你可以通過在值,因此:

echoPair (&number, &string); 

變爲:

echoPair (number, string); 

作爲一個整體,我想你想要的是:

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 

void getData(short int *number, char *string) { 
    printf("\nPlease enter a number greater than zero: "); 
    scanf("%hd", number); 

    printf("Please enter a character string: "); 
    scanf("%s", string); 
} 

void echoPair(short int number, char *string) { 
    printf("Number: %hd Character(s): %s\n", number, string); 
} 

int main (void) { 
    short int number = 0; 
    char string[32] = {0}; 

    printf("Blah blah ..."); 

    getData(&number, string); 
    echoPair(number, string); 
    return(0); 
} 

順便說一句,你永遠不會想看看unboun DED串掃描喜歡:

scanf ("%s", string); 
在產品代碼

。這是一個等待發生的緩衝區溢出漏洞,因爲您無法控制用戶輸入的內容。在您的特定情況下,用戶輸入超過(約)30個字符可能會導致各種奇怪的行爲。

scanf功能是掃描格式的文本,而且也沒有多少東西比用戶輸入:-)

如果你想有一個強大的用戶輸入功能更格式化,看到here

+0

非常感謝,修復了一切。正如你可能知道的那樣,我是編程的新手,這隻會用於練習,但是感謝你對可能溢出的意見,請記住以後再使用! – afiser

1

您聲明局部變量number爲指針,以短整型。然後您將一個指針傳遞給getDataechoPair。所以你傳遞了一個指針,指針是錯誤的類型。可能你想要將數字聲明爲一個簡短的int而不是指針。