gpt4 book ai didi

C:将字符串中的每个字母加倍

转载 作者:行者123 更新时间:2023-12-01 13:27:57 24 4
gpt4 key购买 nike

我现在正在学习 C,我被这个问题困住了。

Input: 'abc'
Output: 'aabbcc'

我坚持使用指针并增加大小缓冲区。见下文

编辑:添加了 main()

#include <stdio.h>
#include <string.h>
int main()
{
char destValue[];
char srcValue[];

//User input
printf("Please enter valid text: " );
scanf("%s", srcValue);

//Copying to memory
memcpy(destValue, srcValue, strlen(srcValue)+1);
char lenghtOfText = strlen(srcValue);

for(int i = 0; i < lenghtOfText; i++) {
tempValue[i] = strcat(tempValue, srcValue);
}
}

每次我运行我的代码时,它总是失败,错误消息是 Abort 6。在搜索时,他们说 tempValue 不会增加缓冲区的大小。

抱歉,如果我的代码无法正常工作,而我只是在学习 C 编程。感谢理解

最佳答案

简单地说,你可以这样做

   #include<stdio.h>
#include<malloc.h>
#define len 10
int main()
{
char *destValue;
char *srcValue;

srcValue = malloc(len * sizeof(char));
destValue = malloc((2 * len * sizeof(char)) + 1);
//User input
printf("Please enter valid text: " );
scanf("%s", srcValue);
int j = 0;
for(int i = 0 ;srcValue[i]!= '\0';i++) {
destValue[j++]= srcValue[i];
destValue[j++]= srcValue[i];
}

destValue[j]='\0';
puts(destValue);

free(destValue);
free(srcValue);

return 0;
}

我希望你能得到这个。

关于C:将字符串中的每个字母加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47498959/

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