gpt4 book ai didi

c - 为什么这些词不附加在 C 中?

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

我正在尝试编写一个将两个单词附加到第三个字符串的函数,并且此函数必须使用 malloc()。在将它放入函数之前,我首先将它写在 main 中。我有:

int main(void){

char *word = "Johnny";
char *word2 = " Boy";
char *buff = malloc(100 * sizeof(char));
printf("%d\n", sizeof(buff));
int ct;
for(ct = 0; ct < strlen(word); ct++){
buff = word;
}
printf("%s\n", buff);
printf("the counter is now %d\n", ct);

buff += ct;
for(ct; ct < 13; ct++){
buff = word2;
}

printf("%s\n", buff);
}

我想让 buff 说“Johnny Boy”,但最后“Johnny”被覆盖了,它只说“Boy”

最佳答案

听着,虽然我们想提供帮助,但 SO 并不是真正意义上的类环境。很明显,您在根本上缺乏对 C 中指针/字符串操作的理解,这是非常基础的 Material 。获取一本关于 C 的更好的书,并将此代码与您的工作进行比较,并研究它,直到您了解差异以及每一步的具体操作。

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

int main(void){
char word[] = "Johnny";
char word2[] = " Boy";
char *temp;
char *buff = malloc(32 * sizeof(char));
if (buff == NULL) {
puts("allocation error");
return 1;
}
for (int ct = 0; ct <= strlen(word); ct++) {
buff[ct] = word[ct];
}
printf("%s\n", buff);
temp = buff + strlen(word);
for (int ct = 0; ct <= strlen(word2); ct++) {
temp[ct] = word2[ct];
}
printf("%s\n", buff);
free(buff);
return 0;
}

关于c - 为什么这些词不附加在 C 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45135038/

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