gpt4 book ai didi

代码不起作用。不断出现段错误(核心已转储)

转载 作者:行者123 更新时间:2023-11-30 21:20:39 24 4
gpt4 key购买 nike

这是一个 C 函数的代码,如果字符串 s1 在字典中出现在字符串 s2 之前,则返回 1;如果 s2 出现在 s2 之前,则返回 -1;如果它们相同,则返回 0。

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

int strcmp_ign_case(char *s1, char *s2){
char *s1Copy;
char *s2Copy;
char *s1Copy3 = s1Copy;
char *s2Copy3 = s2Copy;
char *s1Copy2 = s1;
char *s2Copy2 = s2;

while(*s1Copy2 != '\0'){
*s1Copy3 = *s1Copy2;
*s1Copy3 = tolower(*s1Copy3);
s1Copy3++;
s1Copy2++;
}
*s1Copy3 = '\0';

while(*s2Copy2 != '\0'){
*s2Copy3 = *s2Copy2;
*s2Copy3 = tolower(*s2Copy3);
s2Copy3++;
s2Copy2++;
}
*s2Copy3 = '\0';

while((*s1Copy != '\0') || (*s2Copy != '\0')){
if(*s1Copy > *s2Copy){
return 1;
} else if(*s1Copy < *s2Copy){
return -1;
} else {
s1Copy++;
s2Copy++;
}
}

if((*s1Copy == '\0') && (*s2Copy == '\0')){
return 0;
}
}

我不明白代码有什么问题。请帮助我理解这里的错误。谢谢!

这是我用来测试它的主要内容:

void main(){
char *a1 = "hello";
char *a2 = "hell";
char *a3 = "world";
printf("strcmp_ign_case1: %d\n", strcmp_ign_case(a1,a2));
printf("strcmp_ign_case2: %d\n", strcmp_ign_case(a1,a3));
printf("strcmp_ign_case3: %d\n", strcmp_ign_case(a2,a3));
}

最佳答案

查看评论:

int strcmp_ign_case(char *s1, char *s2){
char *s1Copy; // uninitialized pointer
char *s2Copy;
char *s1Copy3 = s1Copy; // copy of uninitialized pointer
char *s2Copy3 = s2Copy;
char *s1Copy2 = s1;
char *s2Copy2 = s2;

while(*s1Copy2 != '\0'){
*s1Copy3 = *s1Copy2; // dereferenced uninitialized pointer (crash)

关于代码不起作用。不断出现段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36108414/

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