如何使这个函数 return 成为一个字符串

how to make this function return a string

我有这个代码:

static char * display(const u8 array[], int length) {
    int i;
    char *str;
    for (i = 0; i < length; i++) {
        if (i%32 == 0) {
            //printf("\n");
            strcat(str, "\n");
        }
        if (i%8 == 0) {
            //printf(" ");
            strcat(str, " ");
        }
        //printf("%02X", array[i]);
        strcat(str, (char *)array[i]);
    }
    return str;
    /*
    char str[80];
    strcpy (str,"these ");
    strcat (str,"strings ");
    strcat (str,"are ");
    strcat (str,"concatenated.");
    puts (str);
    return 0;
    */
}

最初这段代码是打印一个字符串。我不想让它打印一个字符串,我需要让它返回一个字符串。但它给了我这个错误:

main.c: In function 'display':
main.c:1707:9: warning: passing argument 2 of 'strcat' makes pointer from integer without a cast [ena bled by default]

     strcat(str, array[i]);                                                                      
     ^                                                                                            In file included from main.c:61:0:                                    

/usr/include/string.h:133:14: note: expected 'const char * restrict' but argument is of type 'u8' extern char *strcat (char *__restrict __dest, const char *__restrict __src)
^ sh-4.2# gcc -o main *.c
main.c: In function 'display':
main.c:1707:21: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
strcat(str, (char *)array[i]);

编辑:

构建共享对象并加载:

VALUE generateIt(char *valor) {
  struct NESSIEstruct w;
  u8 digest[DIGESTBYTES];

  int i;
  for(i=0; valor[i]!='[=13=]'; ++i);
  int sizeo = i;

  NESSIEinit(&w);
  NESSIEadd((u8*)valor, 8*sizeo, &w);
  NESSIEfinalize(&w, digest);
  return displayIt(digest, DIGESTBYTES);
}

最重要的是:

#include 'ruby.h'

我还添加了这个:

void
Init_whirlpool(){
  rb_mWhirlpool = rb_define_module("Whirlpool");
  rb_cClass = rb_define_class_under(rb_mWhirlpool, "Class", rb_cObject);
  rb_define_method(rb_cClass, "generate", generateIt, 1);
}

我相信这就是您所需要的

static char *display(const unsigned char array[], int length)
{
    int  i, k;
    char *str;

    str = malloc(3 * length + 1);
    if (str == NULL)
        return NULL;
    k      = 0;
    str[0] = '[=10=]';
    for (i = 0; i < length; i++) {
        char hex[3];

        if (i % 32 == 0)
            str[k++] = '\n';
        if (i % 8 == 0)
            str[k++] = ' ';
        snprintf(hex, sizeof(hex), "%02X", array[i]);

        str[k++] = hex[0];
        str[k++] = hex[1];
    }
    str[k] = '[=10=]';

    return str;
}

snprintf是POSIX,如果报编译错误,改成_snprintf.

并且不要忘记 free 调用函数中的返回值。