gpt4 book ai didi

将 char 数组中的单词转换为包含单个空格的行

转载 作者:行者123 更新时间:2023-11-30 19:28:14 24 4
gpt4 key购买 nike

转换给定的char *input[]到一个带有单个空格的行

输入:

int n =3;
char *result;
char *input[]= {"one", "two", "three" };
result = convertToLine(n, input)

代码

char *convertToLine(int n, char *input[]) {
int size = n* 2;
char* string = (char*)malloc(sizeof(char)*size);
int i = 0;
int k = 0;
while (i <size){
string[i] = *input[k];
string[i+1] = ' ';
i++;
k++;
}
string[n] = '\0';
return string;
}

我的输出:

预期输出:

result = "one two three"

最佳答案

您的代码中有几个错误

int size = n* 2; char* string = (char*)malloc(sizeof(char)*size);

所需的大小必须是最终大小,因此要合并更多空格和最终空字符的字符串长度之和。 n *2 只是字符串数量的两倍,这个不一样

string[i] = *input[k];

不会复制字符串,而只会复制其第一个字符

你可以这样做:

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

char *convertToLine(int n, char *input[]) {
/* compute the needed size,
of course can also use malloc then realloc to avoid that */
int size = 0;
int i;

for (i = 0; i != n; ++i)
size += strlen(input[i]) + 1;

/* copy the strings */
char * string = (char*)malloc(size); /* sizeof(char) is 1 by definition */
char * p = string;

for (i = 0; i != n; ++i) {
strcpy(p, input[i]);
p += strlen(p);
*p++ = ' ';
}
p[-1] = 0;

return string;
}


int main()
{
char *input[]= {"one", "two", "three" };
char * result = convertToLine(3, input);
puts(result);

free(result);
}

执行:

one two three

valgrind下执行:

pi@raspberrypi:/tmp $ valgrind ./a.out
==14749== Memcheck, a memory error detector
==14749== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==14749== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==14749== Command: ./a.out
==14749==
one two three
==14749==
==14749== HEAP SUMMARY:
==14749== in use at exit: 0 bytes in 0 blocks
==14749== total heap usage: 2 allocs, 2 frees, 1,038 bytes allocated
==14749==
==14749== All heap blocks were freed -- no leaks are possible
==14749==
==14749== For counts of detected and suppressed errors, rerun with: -v
==14749== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

关于将 char 数组中的单词转换为包含单个空格的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54390352/

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