gpt4 book ai didi

c - 指向字符数组第一个字符的指针?

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:54 24 4
gpt4 key购买 nike

编辑:显然我必须先在 pigLatin 方法的开头声明 char *first ,然后在该方法中将其初始化为 &word[counter] 。有谁知道这是为什么?我正在使用 Visual Studio 2010。

我无法弄清楚为什么会出现编译时错误。有问题的代码:

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

char *pigLatin(char *word)
{
if (word[0] == 'a' || word[0] == 'e' || word[0] == 'i'
|| word[0] == 'o' || word[0] == 'u')
{
char yay[] = "yay";
strcat(word, yay);
return word;
}
else
{
int length = strlen(word);
int counter = 0;
char addOn[] = "";
char remainder[] = "";
char yay[] = "yay";
printf("%s", yay);

char *first = &word[counter];
printf("%c", *first); // error is here, don't know why it doesn't print
return word;
}
}


int main()
{
char hello[] = "hello";
pigLatin(hello);
printf("%s", hello);
getch();
return (0);
}

1>------ 构建开始:项目:Program_One,配置:发布 Win32 ------

1>程序一.c

1>programone.c(12):警告 C4996:“strcat”:此函数或变量可能不安全。考虑改用 strcat_s。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。有关详细信息,请参阅联机帮助。

1>programone.c(24):错误 C2143:语法错误:缺少“;”在“类型”之前

1>programone.c(25): error C2065: 'first' : undeclared identifier

1>programone.c(25): error C2100: 非法间接寻址

========== 构建:0 成功,1 失败,0 最新,0 跳过 ==========

我不明白为什么我指向数组“hello”第一个字符的指针没有正确打印。

提前致谢!

最佳答案

您没有将指针变量分配给指向第一个字符的地址。您正在将字符本身的值分配给指针变量,这就是编译器出错的原因。

你需要改变这一行:

char *first = word[counter]; 

对此:

char *first = &word[counter]; 

或者,只是这样做:

char *pigLatin(char *word)   
{
int counter = 0;
printf("%c", word[counter]);
return word;
}

更新:即使代码确实通过了编译,也是危险的。关于 strcat() 的编译器警告有效。您没有分配足够的内存来将 "yay" 附加到以元音开头的输入词。要真正使这段代码更安全,您应该使用 std::string 类而不是原始指针:

#include <conio.h> 
#include <string>

std::string pigLatin(const std::string &word)
{
switch( word[0] )
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return word + "yay";
}

int length = word.length();
int counter = 0;
//...

printf("%c", word[counter]);
return word;
}

int main()
{
std::string word = pigLatin("hello");
printf("%s", hello.c_str());
getch();
return 0;
}

关于c - 指向字符数组第一个字符的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10825699/

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