带有空指针的字符串连接

我有一个通用的打印函数,旨在返回带有空指针类型和一些char *类型变量的串联输出字符串。

  1. Is it possible to print void *
  2. If not, then can someone please at least review the code about malloc and strcat.

功能

const char * print(char *name, void *data, char *type) {
    char *str = malloc(sizeof(name) + sizeof(data) + sizeof(type)); // do I need + 1 for null?
    strcat(str, name); // name is never NULL
    if (data) strcat(str, data); // data can be NULL
    if (type) strcat(str, type); // type can be NULL
    return str;
}

用法

struct {int value;} obj = {5};
char *result = print("Test", &obj, "type");
puts(result);
评论