当前位置:  开发笔记 > 程序员 > 正文

初学C程序员需要指针帮助(我认为)

如何解决《初学C程序员需要指针帮助(我认为)》经验,为你挑选了1个好方法。

我是初学程序员,我正在学习我的第一语言,C.

我主要从Deitel和Deitel的C How to Program一书中学习,但也使用了大学的示例任务和事情,但是我被困在一个.

我对指针有一个非常基本的理解 - 在变量前添加&使得它打印一个地址,*使用指针来使用存储在该地址的值等.

我编写的这段代码用于计算两个数字的最大(最大?)公分母,实际上并不需要或涉及指针.它使用两个函数,逻辑是正确的,因为如果我从第二个函数执行它,它会打印出正确的屏幕答案,而不是将它返回到main.这就是问题所在.

当第二个函数返回答案值时,由于某种原因它返回我只能假设的指针.我不知道为什么会这样做.我将能够使用它并将其转换为查找值 - 但它似乎是第二个函数的本地指针并被写入.网上没有我能找到或在我的书中的任何内容让我知道如何解决问题.

谢谢,如果你已经读到这么远了.我太过漫无边际了.

这是我的代码和输出.任何帮助或指针(借口双关语)将不胜感激.我知道我可以在第二个函数中打印它,但我更愿意知道它是如何以及为什么它不会像我希望的那样返回值.

#include 
int greatestCD (int num1, int num2);

int main(void)
{
    int a=0, b=0;
    int result;
    printf("Please enter two numbers to calculate the greatest common denominator from\n");
    scanf("%d%d", &a, &b);
    result = greatestCD (a,b);
    printf("Using the correct in main way:\nThe greatest common denominator of %d and %d is %d\n",a,b, result);
}

int greatestCD (int num1 ,int num2)
{ 

    if (num2==0){
        printf("Using the cheaty in gcd function way:\nThe greatest common denominator is %d\n",num1);
        return num1;
    } else {
        greatestCD(num2,(num1%num2));
    }    
}

输出(使用12和15 - 答案应为3)

C:\Users\Sam\Documents\C programs>gcd
Please enter two numbers to calculate the greatest common denominator from
12
15
Using the cheaty in gcd function way:
The greatest common denominator is 3
Using the correct in main way:
The greatest common denominator of 12 and 15 is 2293524

frankodwyer这样一个简单的解决方案.这是我无法发现或不知道的小事.所以返回的不是指针而只是垃圾?

太感谢了.



1> frankodwyer..:

您在函数largestCD()的最后一行中缺少'return'语句

greatestCD(num2,(num1%num2));

做了

return greatestCD(num2,(num1%num2));

(你可能还有进一步的调试要做,但这就是它返回垃圾的原因......你没告诉它还有什么可以返回)

编辑:我还建议在将来编译时打开所有编译器警告...如果你正在使用gcc,那么尝试将标志-Wall添加到你的编译命令.当你做的事情可能会导致像这样的错误时,这应该警告你.(并非每一个这样的警告都是必然的错误,因此是"警告",但它通常表示可能存在问题.)

推荐阅读
家具销售_903
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有