gpt4 book ai didi

C程序复制字符串而不使用具有足够内存的strcpy()

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

我正在尝试得到这个输出:

Comparing results of concat and strcat ...
strcmp("Plain old stringTroy", "Plain old stringTroy") says: 0

如果两个字符串参数相同,则 strcmp 返回 0。如果结果为 0,则 concat 的行为与库函数 strcat 完全相同。

这就是我的 concat 方法。

#define MAXSIZE 32       
void concat(char dest[], char src[])
{
int i=length(src);
int j=0;
for(j; j<src[j] !='\0'; j++) {
dest[i+j] = src[j];
}
dest[i+j] = '\0';
}

长度方法是:

 int length(char str[])                                                      
{
// Add code here to return the length of the
// string str without using the strlen function
// Do not count the null character '\0'
// in computing the length of the string
int len=0;
int i;
for(i=0;i<str[i];i++) {
len++;
}
return len;
}

这是我的主要内容

int main()                                                                  
{
// Variable declarations for all parts
char str2[] = "Troy";
char str4[] = "Plain old string";
char str6[MAXSIZE];
// Part 6
printf("\n----- Part 6 -----\n");
// Make a copy of the destination string first, to be reused later
strcpy(str6, str4);
concat(str4, str2);
strcat(str6, str2);
printf("Comparing results of concat and strcat ...\n");
printf("strcmp(\"%s\", \"%s\") says: %d\n",
str4, str6, strcmp(str4, str6)
);

return 0;
}

这是我运行时的输出:

----- Part 6 -----
Comparing results of concat and strcat ...
strcmp("PlaiTroy", "Plain old stringTroy") says: -1

第一个字符串与第二个字符串不同,这就是我得到 -1 的原因。我的问题出在我的 concat 方法中,但我似乎无法理解为什么它不能很好地执行。是因为空格吗? 0和'\0'执行的不好吗?

最佳答案

您的代码中存在多个问题:

  • length 中的循环测试函数不正确:而不是 i < str[i] ,应该是:

     for (i = 0; str[i] != '\0'; i++)
  • 同样的问题在 concat功能。将循环更改为:

     for (j = 0; src[j] != '\0'; j++) {
  • 也在concat功能,i应该是 dst 的长度, 不是 src 的那个.您可以使用 len而不是 i对于这个变量。

  • 数组str4在函数中 main concat 末尾没有可用空间附加任何东西。以这种方式定义更大的尺寸:

    char str4[MAXSIZE] = "Plain old string";      

修改后的版本:

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

#define MAXSIZE 32

void concat(char dest[], char src[]) {
int len = length(dest);
int j;
for (j = 0; src[j] != '\0'; j++) {
dest[len + j] = src[j];
}
dest[len + j] = '\0';
}

int length(char str[]) {
int len = 0;
int i;
for (i = 0; i < str[i]; i++) {
len++;
}
return len;
}

int main(void) {
// Variable declarations for all parts
char str2[MAXSIZE] = "Troy";
char str4[MAXSIZE] = "Plain old string";
char str6[MAXSIZE];
// Part 6
printf("\n----- Part 6 -----\n");
// Make a copy of the destination string first, to be reused later
strcpy(str6, str4);
concat(str4, str2);
strcat(str6, str2);
printf("Comparing results of concat and strcat ...\n");
printf("strcmp(\"%s\", \"%s\") says: %d\n",
str4, str6, strcmp(str4, str6));
return 0;
}

关于C程序复制字符串而不使用具有足够内存的strcpy(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46924421/

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