1613551 发表于 2022-5-25 15:05:02

这个代码运行不了,有人知道是为什么吗?

#include <stdio.h>
char *getWord(char);
char *getword(char c)
{
    switch (c)
    {
    case 'A':
      return "Apple";
    case 'B':
      return "Banana";
    case 'C':
      return "Cat";
    case 'D':
      return "Dog";
    default:
      return "None";
    }
}
int main()
{
    char input;
    printf("请输入一个字母:");
    scanf("%c", &input);
    printf("%s\n", getWord(input));
}

傻眼貓咪 发表于 2022-5-25 15:09:23

函数返回的是 char* 指针,请问你返回的是什么?

1613551 发表于 2022-5-25 15:18:29

傻眼貓咪 发表于 2022-5-25 15:09
函数返回的是 char* 指针,请问你返回的是什么?

我返回的也是char类型的指针啊,字符串不就是指向char类型的指针吗

1613551 发表于 2022-5-25 15:19:31

我是完全照抄小甲鱼的,我不知道为什么不行{:10_266:}

1613551 发表于 2022-5-25 15:20:22

https://www.bilibili.com/video/BV17s411N78s?p=3004:50

wp231957 发表于 2022-5-25 15:26:41

傻眼貓咪 发表于 2022-5-25 15:09
函数返回的是 char* 指针,请问你返回的是什么?

原来这玩意还能这样用啊
#include <stdio.h>

char* test(int a)
{
    if (a%2)return "我是奇数!";
    else return "我是偶数";
}

int main()
{

    printf("%s\n",test(55));
    printf("%s\n",test(88));
    return 0;      
}

/*
PS D:\wp> ./ct8
我是奇数!
我是偶数
PS D:\wp>
*/

jhq999 发表于 2022-5-25 15:33:03

printf("%s\n", getword(input));

傻眼貓咪 发表于 2022-5-25 15:33:13

1613551 发表于 2022-5-25 15:18
我返回的也是char类型的指针啊,字符串不就是指向char类型的指针吗

看漏了,抱歉。你的代码W 大写写成小写了

wp231957 发表于 2022-5-25 15:36:05

#include <stdio.h>

char *getword(char c)
{
    switch (c)
    {
    case 'A':
      return "Apple";
    case 'B':
      return "Banana";
    case 'C':
      return "Cat";
    case 'D':
      return "Dog";
    default:
      return "None";
    }
}
int main()
{
    char input;
    printf("请输入一个字母:");
    scanf("%c", &input);
    printf("%s\n", getword(input));
}

/*
PS D:\wp> ./ct8
请输入一个字母:A
Apple
PS D:\wp> ./ct8
请输入一个字母:B
Banana
PS D:\wp> ./ct8
请输入一个字母:C
Cat
PS D:\wp> ./ct8
请输入一个字母:D
Dog
PS D:\wp>
*/


程序没问题,就是你的两个GETWORD 拼写不一致,导致没有链接成功exe所以会出现你图片中的0.exe没有找到的提示

傻眼貓咪 发表于 2022-5-25 15:36:19

wp231957 发表于 2022-5-25 15:26
原来这玩意还能这样用啊

没错,C 语言就是玩指针,一堆题目如:链表、二叉树等,就是把指针玩遍。想到 Python 要写二叉树,因为没有指针特性,会吐。

jhq999 发表于 2022-5-25 15:36:28

本帖最后由 jhq999 于 2022-5-25 15:41 编辑

转自csdn
一旦有字符串常量在运行期间创建,就会在内存中一直保持到程序结束,当使用相同的字符串常量的时候,不会再创建字符串常量,而是指向之前的那个。因此字符串常量是贯穿整个程序的生命周期的。
char *s0="hello";
void a()
{
char *s1="hello";
printf("%0x\n",s1);
s1="world";
}
void b()
{
   char *s2="hello";
   printf("%0x\n",s2);
   s2="world";
}
int main()
{
char *s3=(char *)0;
printf("%0x\n",s0);
a();
b();
s3="hello";
printf("%0x\n",s3);
return 0;
}

Suaky 发表于 2022-5-25 17:48:38

配置环境问题
页: [1]
查看完整版本: 这个代码运行不了,有人知道是为什么吗?