【发布时间】:2017-06-01 20:28:17
【问题描述】:
在对 Java 有了一定程度的适应之后,我现在正努力扩大自己的视野并尝试 C 编程。但是,即使访问了多个视频和网站,我似乎也无法完全理解 C 中的指针。
下面的代码应该从用户那里获取两个字符串,获取它们的长度,然后将长度相互比较。然后程序应该通过指针返回两个名称中最长的一个(非常小心地返回直到换行符的长度,而不是变量的分配大小)。因此,当用户输入 'Peterson'(name1) 和 'Thisisareallylonglastname'(name2) 时,程序应通过指针 / name2 连接返回 'Thisisareallylonglastname'。
我遇到的问题是,当尝试运行代码(使用 Eclipse Neon C/C++ IDE 编写,使用 MinGW 编译器)时,我在控制台中没有输出。我相当确定我已经在 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);
}
【问题讨论】:
-
您需要了解
printf的工作原理,因为printf(size1)是不正确的。 -
始终使用正确的格式说明符,即
printf(size1);->printf("%d", size1);&printf(size2);->printf("%d", size2);& 我猜是 printf(*ch);应该是printf("%s", ch); -
在玩过 Java 之后,尝试 C++ 而不是 C 会更“自然”(同样的 OOP用于输入/输出...)。
-
从不使用
gets。它不再是 C 标准的一部分。请改用fgets。