我想用这段代码生成的字符串返回一个 char* 指针:
char *printFilmRating(char *buffer, struct rating_film *handler) {
if(handler!=NULL) {
sprintf(buffer + strlen(buffer), "Valutazione inserita il %02d/%02d/%d alle %02d:%02d:%02d\n",handler->date_rating->day,handler->date_rating->month,handler->date_rating->year,handler->date_rating->hour,handler->date_rating->minutes,handler->date_rating->seconds);
sprintf(buffer + strlen(buffer), "Valutatore: %s\n",handler->nickname);
sprintf(buffer + strlen(buffer), "Valutazione: %f\n",handler->rate_film);
sprintf(buffer + strlen(buffer), "Commento:\n%s\n",handler->text);
sprintf(buffer + strlen(buffer), "\n");
buffer=printFilmRating(buffer, handler->next);
}
return buffer;
}
实际上,这个函数将读取一个列表,因为列表指针不为空。但是在函数的末尾,函数将返回一个(空)字符串,我认为是因为它将返回堆栈上的第一个实例,它具有(空)。如何返回列表中所有红色的信息?
最佳答案
由于这对于评论来说太大了,而且它实际上可能会回答你的问题,所以这里有一些东西给你。
我成功编译了以下代码(使用 gcc -std=c99
):
#include <stdio.h>
#include <string.h>
struct sample {
struct sample *next;
int value;
};
char *printSample(char *buf, struct sample *handle){
// effectively the same code as OP
if( handle ){
sprintf(buf + strlen(buf), "Value: %d\n", handle->value);
buf=printSample(buf, handle->next);
}
return buf;
}
int main(){
char buffer[400] = {""}; // NOTE: initialize string to nulls
struct sample mysample = { .next = 0, .value = 1 };
struct sample mysample1 = { .next = &mysample, .value = 2 };
struct sample mysample2 = { .next = &mysample1, .value = 3 };
struct sample mysample3 = { .next = &mysample2, .value = 4 };
printf("%s\n", printSample(buffer, &mysample3));
return 0;
}
我得到了以下输出:
Value: 4
Value: 3
Value: 2
Value: 1
这是意料之中的。您发布的代码效率不高或不一定安全,但它应该可以工作。如果输出不是您想要的,则说明其他地方有问题。
关于c - 如何从递归查看的列表中使用sprintf保存字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25851408/