如何使用列表中的sprintf保存字符串递归查看

时间:2014-09-15 15:18:16

标签: c string list printf buffer

我想返回一个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;
    }

实际上,此函数将读取列表,因为列表指针不为空。但是在函数结束时,函数将返回一个(null)字符串,我想因为它将返回堆栈上的第一个实例,它具有(null)。如何从列表中返回红色的所有信息?

1 个答案:

答案 0 :(得分:2)

由于这对评论来说太大了,事实上它可能会回答你的问题,这里有适合你的事。

我成功编译了以下代码(使用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

这是可以预料的。您发布的代码效率不高或必然安全,但它应该有效。如果输出不是您想要的,那么您在其他地方就会遇到问题。