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而不是指针。