gpt4 book ai didi

C 编程 - 指针出现问题,没有控制台输出

转载 作者:行者123 更新时间:2023-11-30 16:51:37 25 4
gpt4 key购买 nike

在对 Java 有了一定程度的熟悉之后,我现在正在尝试扩展我的视野并尝试 C 编程。然而,即使访问了多个视频和网站,我似乎也无法理解 C 中的指针。

下面的代码应该从用户处获取两个字符串,获取它们的长度,然后将长度相互比较。然后,程序应该通过指针返回两个名称中最长的一个(特别注意返回换行符之前的长度,而不是为变量分配的大小)。因此,当用户输入“Peterson”(name1) 和“Thisisareallylonglastname”(name2) 时,程序应通过指针/name2 连接返回“Thisisareallylonglastname”。

我遇到的问题是,当尝试运行代码(使用 MinGW 编译器在 Eclipse Neon C/C++ IDE 中编写)时,我在控制台中没有得到任何输出。我相当确定我已在 Windows 中正确设置了 MinGW 安装的路径,但为了确保我也已将环境手动添加到项目中。在我对指针的困惑和通常是一个蹩脚的编码员之间,我不确定我的程序的(无疑是新手)错误是什么。我在 Neon IDE 中没有收到任何类型的错误。

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

int main(void)
{

/* Two variables that take family names' input from the user with a maximum length of 256 */
char name1[256];
char name2[256];
char *ch = NULL;

printf("When two people marry there can sometimes be a debate which last/family name will henceforth be used (as a hyphenated last name is not always feasible.");
printf("A simple way to avoid squabbles is to simply take the longest family name of the two (soon-to-be) partners.");
printf("This program will take your name inputs and compare their length against one another; it will then return the longest name to be put on the document.");

printf("Enter your last name for 1 :");
gets(name1);
printf("Enter your last name for 2 :");
gets(name2);

int size1 = strlen(name1);
printf("Length of name 1:");
printf(size1);

int size2 = strlen(name2);
printf("Length of name 2:");
printf(size2);

if (size1 > size2)
{
ch = &name1;
}
else
{
ch = &name2;
}

if(!ch)
{
printf("The largest family name found is:");
printf(*ch);
}

return(0);

}

最佳答案

一个主要问题是您的最终输出处于条件 if (!ch) 下 - 用英语表示“如果指针 ch null-值”。由于它指向两个(非null)内存位置之一,因此该检查永远不会通过。

如果将其更改为 if (ch) (或者只是省略检查,因为我们知道它不是 null)并修复 printf > 别人在评论中指出的问题,我想你会得到更好的结果。

关于C 编程 - 指针出现问题,没有控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41702841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com