gpt4 book ai didi

c - 程序在关闭时崩溃

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

所以,这是我第一次在这里发帖,我会尽量具体一些。我必须为我的学校制作一个程序,上面写着:

首先写一个获取一个字符并返回的函数:

  1. 如果是大写字母则相同。
  2. 如果是小写字母,则为大写字母。
  3. 如果是数字,则为反斜杠 ('\')。
  4. 在任何其他情况下使用星号 ('*')。

然后,使用您的函数制作一个程序,获取字符串并在函数更改后重新打印它。它应该一直要求一个新的字符串,直到用户键入“退出”,在这种情况下,将打印“再见!”然后退出。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

char fnChange(char c)
{
if (c > 'a'-1 && c < 'z'+1)
c = c - 32;
else if (c > '0'-1 && c < '9'+1)
c = '\\' ;
else if ( c > 'A'-1 && c < 'Z'+1)
c = c;
else
c = '*';
return c;
}


int main()
{
int i, refPoint;
char *str = (char*)malloc(10);
//without the next one, the program crashes after 3 repeats.
refPoint = str;
while (1==1) {
printf("Give a string: ");
str = refPoint;//same as the comment above.
free(str);
scanf("%s",str);
if (*str == 'Q' && *(str+1) == 'U' && *(str+2) == 'I' && *(str+3) == 'T') {
// why won't if (str == 'QUIT') work?
free(str);
printf("Bye!"); //after printing "Bye!", it crashes.
system("pause"); //it also crashes if i terminate with ctrl+c.
exit(EXIT_SUCCESS); //or just closing it with [x].
}
printf("The string becomes: ");
while (*str != '\0') {
putchar(fnChange(*str));
str++;
}
printf("\n");
}
}

最佳答案

free(str);
scanf("%s",str);

不行-不行,释放后不允许使用动态分配的内存。最重要的是,您在循环内再次释放它。

这样做是未定义的行为。这几乎可以肯定是您崩溃的原因。

其他几个问题。您可以使用 <=而不是 <使您的代码更具可读性,例如:

if  ((c >= 'a') && (c <= 'z')) ...

使用魔数(Magic Number),例如32几乎总是一个坏主意。如果您使用的是字母连续的编码(例如 ASCII),您可以:

c = c - 'A' + 'a';

将大写字母变成小写字母。

然而,您真正应该做的是使用 toupper()tolower() (以及 isupper()islower(),以检测大小写)因为字母保证是连续的。

表达式str == 'QUIT'不会按照你的想法去做,因为'QUIT'不是字符串。相反,它是一个多字节字 rune 字。然而,即使str == "QUIT"不会按照您的想法去做,因为在 C 中比较字符串的正确方法是:

if (strcmp (str, "QUIT") == 0) ...

关于c - 程序在关闭时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25640316/

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