gpt4 book ai didi

c - C 中的指针、字符串和函数

转载 作者:行者123 更新时间:2023-11-30 15:22:38 26 4
gpt4 key购买 nike

我错过了一周的类(class),其中他们介绍了指针,但我无法从类里面获得笔记,但我的硬件到期了,我仍然不明白如何使用指针从函数传递字符串运行...下面是我的代码,我意识到其中的指针已经困惑不堪,但我尝试阅读其他论坛,但只是迷路了。如有任何帮助,我们将不胜感激。

#include <stdio.h>

char* returnInPlace(char);
int palindrom(char, char );

main(void)
{
char newString[20];

printf("Enter a string: ");
scanf("%s",&newString);

char flippedString[20]=reverseInPlace(newString);
int palCheck= palindrome(newString, flippedString);

if (palCheck==0)
printf("\n\tThe reverse string is %s, so we don't have a palindrome.", flippedString);
else
printf("\n\tThe reverse string is %s, so we do have a palindrome.", flippedString);

}

char* reverseInPlace(char newString)
{
int iterator;
char flipped[20];
char *ptr1;
for(iterator=0;iterator<20;iterator++)
{
flipped[iterator]=firstString[19-iterator];
}
ptr1=flipped[];
return *ptr1;
}

int palindrome(char newString, char flippedString)
{
int iterator;
int palCheck=1;
for(iterator=0;iterator<20;iterator++)
{
if (firstString[iterator]==secondString[iterator])
continue;
else
{
palCheck=0;
break;
}
}
return palCheck;
}

最佳答案

问题1

char*reverseInPlace(char newString)中,您正在使用

return *ptr1;

这是错误的。您可能想要的是

return ptr1;
<小时/>

问题2

ptr1=flipped[];

是错误的。在这里,您分配局部变量flipped的基地址并返回该值。 flipped 将在 reverseInPlace() 执行完成后不再存在。您需要使用动态内存分配。

<小时/>

问题3

char flippedString[20]=reverseInPlace(newString);

是错误的。除非在定义时进行初始化,否则不能使用 =分配数组。

<小时/>

问题4

char* reverseInPlace(char newString)

从调用它的方式来看,这个函数定义看起来是错误的。也许你想要的是

char* reverseInPlace(char* newString)

相反。

......也许还有更多。强烈建议在开始编写代码之前阅读一些有关指针和 C 基础知识的好书。

关于c - C 中的指针、字符串和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29167571/

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