简体   繁体   中英

How to use format specifiers with strdup?

How to use format specifier with strdup? I am trying to do something like this.

char arr[10] = "acbde";
char* s = strdup("Hello..I am %s", arr);

But this does not work.

You can't use the function strdup for this. Instead you should use snprintf . Here is a basic example on how you should do it.

char *arr = "acbde";
char str[100]; // set this to your maximum length

snprintf(str, sizeof(str), "Hello..I am %s", arr);

Here is a more complete example on how it can be used.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main(void) {
  char *arr = "acbde";
  char *str;

  int length = snprintf(NULL, 0, "Hello..I am %s", arr);
  assert(length >= 0); // TODO add proper error handling
  str = malloc(sizeof(char) * (length + 1));
  snprintf(str, length+1, "Hello..I am %s", arr);

  printf("%s [%d]\n", str, length);
  free(str);
}

Try use g_strdup_printf() . But should understand - you must free memory after using this function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM