gpt4 book ai didi

c - 这段代码有什么问题?

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

正如您在下面看到的,我已经创建了一个小程序来使用 C 连接 2 个字符串,正如您可能想象的那样,这段代码不起作用,我已经通过使用数组表示法而不是指针自行更正了它,并且它可以正常工作很好,但是我仍然不确定为什么我的代码几乎无法成为我更正代码的副本。

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

void concatena(char *str1, char *str2){
char *strAux;
int mover;
mover = 0;
strAux = (char *)(malloc(strlen(str1) + strlen(str2)+2));
*(strAux) = '\0';
if(str1 == '\0')
*strAux = '\0';
else
while(str1 != '\0'){
*(strAux+mover++)=*(str1++);
}
if(str2 == '\0')
*strAux = '\0';
else
while(str2 != '\0'){
*(strAux+mover++)=*(str2++);
}
strAux='\0';
str1=strAux;
printf("%s", str1);
free(strAux);
}

我仍然是 C 初学者(是的,我知道有像 string.h 这样的库,我问这个是出于学术原因)并且我被告知字符指针和数组是同一回事,这让我很困惑。

非常感谢任何帮助。

最佳答案

我看到的第一个问题是这个部分:

if(str2 == '\0')
*strAux = '\0';

就在这段代码之前,您已经用 str1 中的字符串填充了 strAux
然后,如果 str2 为空,您会突然在 strAux 的开头放置一个空终止符,从而消除您到目前为止所做的所有工作!

我想你的意图是:

if(*str2 == '\0')
*(strAux+mover) = '\0';

在你的 str2 循环之后又是同样的事情,你有代码:

strAux='\0';

同样,这会在 strAux 的开头放置一个空终止符,有效地在新创建的字符串开始之前结束它。


以下是我将如何重写您的代码:

void concatena(char *str1, char *str2){
char *strAux;
int mover = 0;

strAux = (char *)(malloc(strlen(str1) + strlen(str2)+1)); // Changed to +1, NOT +2
*(strAux) = '\0'; // Start the string as (empty)

while(*str1 != '\0'){ // Copy the first string over.
*(strAux+mover++)=*(str1++);
}

while(*str2 != '\0'){ // Copy the second string over.
*(strAux+mover++)=*(str2++);
}

*(strAux+mover)='\0'; // End the new, combined string.

printf("%s", strAux); // Show the results.
free(strAux);
}

关于c - 这段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7410356/

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