c - 为什么 main 中的调试语句与每个子函数中的调试语句产生的结果不同?

标签 c pointers

为什么 main 中的调试打印语句与每个子函数中的调试打印语句产生的结果不同?调试语句不缩进。谢谢!

代码:

//function declarations
void    getData (char vehicleType);
void    getVType (char* vehicleType);
int main()
{
//local declarations
    char    vehicleType;                //type of vehicle    - user input

//statements
    getData (vehicleType);
printf("\nin main vehicleType: %c\n", vehicleType);

    return 0;
}

void    getData (char vehicleType)
{
    getVType(&vehicleType);
printf("\nin getData vehicleType: %c\n", vehicleType);
}

void    getVType(char* vehicleType)
{
    printf("vehicle type: ");
    scanf("%c", vehicleType);
printf("\nin getVType, you entered: %c\n", *vehicleType);
}

输出:

vehicle type: c

in getVType, you entered: c

in getData vehicleType: c

in main vehicleType:

Process returned 0 (0x0)   execution time : 1.949 s
Press any key to continue.

最佳答案

main 中,vehicleType 从未设置过,因此它的值未定义。其他方法之所以有效,是因为您是通过引用(指针)而不是值传递的。

要将值返回到 main,您需要返回它

c = getData();

char    getData ()
{
    char vehicleType
    getVType(&vehicleType);
    printf("\nin getData vehicleType: %c\n", *vehicleType);
    return vehicleType;
}

或者通过引用传递

getData(&c);

void    getData (char *vehicleType)
{
    getVType(vehicleType);
    printf("\nin getData vehicleType: %c\n", *vehicleType);
}

关于c - 为什么 main 中的调试语句与每个子函数中的调试语句产生的结果不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32751968/

相关文章:

更改函数中的指针字符值

c - C 中指针的奇怪段错误

C - 创建链表的函数仅返回第一个节点

c - 如何避免段错误?

对将字符串获取到二维数组感到困惑

c - D-Bus如何创建和发送一个Dict?

c - 用于个别类型的环形缓冲区处理程序

C++ 抛硬币模拟器不工作

c - 什么时候指向数组的指针有用?

c - restrict 关键字有多严格?