gpt4 book ai didi

c++ - 指针和 Char 数组问题

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

好吧,这段代码确实编译了,它确实运行了,但它没有给我原始或反向数组的正确输出,只是乱码。我花了最后 4 个小时试图看看哪里出了问题(之前它根本不起作用,现在我至少可以输出应该是 C 字符串的内容,我得到了乱码)。有人请帮我看看我哪里错了。

#include <iostream>
#include <cstring>
using namespace std;


char* getInput();
char* getReverse(char[], int);
void displayResults(char *, char *);

const int MAX_SIZE = 21;

int main()
{
//program to create a c-string and then output the reverse order
char *original;
char *reverse;
original = getInput();
int originalSize = strlen(original);
reverse = getReverse(original, originalSize);
displayResults(original, reverse);
return 0;
}

/***************************************************
Definition of function- getInput: *
prompts the user to enter in a line of text to a *
max amount of characters. Returns a pointer to the *
C-string array. *
****************************************************/
char* getInput()
{
char *originalptr;
char original[MAX_SIZE];
cout << "Enter a word or line of text up to a max of 20 characters\nand will have it output in reverse!" << endl;
cin.getline(original, MAX_SIZE);
originalptr = original;
return originalptr;
}

char* getReverse(char *reverseThis, int size)
{

char* reverseOutput;
char reverse[MAX_SIZE];
int counter = 0;
while(*reverseThis != '\0')
{
reverse[counter] = *(reverseThis + (size - counter));
reverseThis++;
counter++;
}
reverseOutput = reverse;
return reverseOutput;

}

void displayResults(char *original, char *reverse)
{
cout << "\nYou originally entered: " << original << endl;
cout << "In reverse order: " << reverse << endl;
}

最佳答案

在“getReverse”中,您在 STACK 上分配变量“reverse”,这意味着当函数返回时数据将消失,无论有多少指针引用该数据。

我会在 main 中用“char reverse[MAX_SIZE];”声明“reverse”,然后让函数接受一个参数“char reverse[]”,然后函数将修改该参数。

关于c++ - 指针和 Char 数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20015925/

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