[英]How do I get all elements from a struct array, and add them into a string in c?
char str[vector_total(&final_clause)];
for(int i = 0; i<vector_total(&final_clause); i++)
{
printf("%s ", (char*) vector_get(&final_clause,i)); // outputs b a -c a a -c -c
strcpy(str, (char*) vector_get(&final_clause,i));
}
printf("%s", str); //only prints -c (last )
remove_repeatation(str); // removes repeats. Expected: b a-c
Evidently its replacing 'str' everyloop.显然它取代了'str'everyloop。 So what is the best way to fix this?那么解决这个问题的最佳方法是什么? Not sure if this is a easy question but I just haven't been able to crack it using different approaches.不确定这是否是一个简单的问题,但我只是无法使用不同的方法破解它。
char str[vector_total(&final_clause)];
too small.太小。
size_t len = vector_total(&final_clause);
char str[len*2 + 1]; // might be enough
//only prints -c (last ) //只打印 -c (last )
Code copies vector_get()
into the same location so this is expected.代码vector_get()
复制到同一位置,因此这是意料之中的。
Perhaps use strcat()
and str[0] = 0;
也许使用strcat()
和str[0] = 0;
for the first strcat(str, ..
to work.第一个strcat(str, ..
工作。
You need to use strcat
instead of strcpy
.您需要使用strcat
而不是strcpy
。 strcpy
replace the content of str
by the result of vector_get()
when strcat
concatenate str
and vector_get()
. strcpy
当strcat
连接str
和vector_get()
vector_get()
的结果替换str
的内容。
This should fix your problem:这应该可以解决您的问题:
char str[vector_total(&final_clause)];
char *result = NULL;
str[vector_total(&final_clause)] = '\0;
for(int i = 0; i<vector_total(&final_clause); i++)
{
printf("%s ", (char*) vector_get(&final_clause,i)); // outputs b a -c a a -c -c
result = realloc(result, (sizeof(char) * strlen(vector_get(&final_clause,i));
result = strcat(result, (char*) vector_get(&final_clause,i));
}
printf("%s", str);
remove_repeatation(str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.