gpt4 book ai didi

c - 使用 scanf 或 gets 进行输入的运行时异常

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

我试图使用此代码从控制台获取输入,但每次我尝试运行它并输入第一个可能的输入时,它都会在某个内存位置给我运行时异常。我正在使用 Visual Studio 2010。我在使用 MingW 和 Dev C++ 时遇到了同样的问题。然而,代码在旧的 TurboC3 编译器上运行良好。

int Nowhere(int x);
...
char* AtBashEncrypt(char* message);
char* AtBashDecrypt(char* encrypted);

int main()
{
char *input = "", *ciphertext = "", *plaintext = "";
system("cls");
printf("AtBash Cipher\nEnter a string to be encrypted: ");
gets(input); //this is where I get the error
ciphertext = AtBashEncrypt(input);
...
getch();
}

可能出了什么问题?

最佳答案

 char *input = "";

是指向驻留在只读存储器中的字符串文字的指针,您无法修改其内容。任何这样做的尝试都会导致未定义的行为。您需要的是一个数组。

#define MAX_SIZE 256
char input[MAX_SIZE]="";

好读:
What is the difference between char a[] = ?string?; and char *p = ?string?;?

此外,您应该 use fgets instead of gets

关于c - 使用 scanf 或 gets 进行输入的运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15286416/

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