简体   繁体   中英

use const char array in snprintf in c

I'm very new comer to C. I've this type of code and when I tried to execute it this warning message showed up "passing argument 1 of 'snprintf' discards 'const' qualifier from pointer target type" and nothing happened.

What I did wrong? Thank you

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

int main()
{
  int i;
  const char *msg[3] = {"Hello", "Good Morning", "Hello World"};
  const char *strings[];


  for(i=0; i<3; i++)
  snprintf(strings[i], 20, "%s %d", msg[i], i);

  for(i=0; i<3; i++)
  printf("strings[%d]: %s\n", i, strings[i]);

  return 0;
}

snprintf(strings[i], 20, "%s %d", msg[i], i);

that tries to write into strings[i] . Since it's been declared as constant, compiler just refuses to do that because it violates the contract.

But here, it's even more serious: strings[i] doesn't have any allocated memory for the strings or even the pointers (!), so removing the const qualifier would result in undefined behaviour when running your program.

You need to allocate space for each string you want to print, like this

char *strings[3];
for (i = 0; i < 3 ; ++i) {
    size_t length = snprintf(NULL, 0, "%s %d", msg[i], i);
    strings[i] = malloc(length + 1);
    if (string[i] != NULL) {
        snprintf(strings[i], length, "%s %d", msg[i], i);
    }
}

for (i = 0; i < 3 ; ++i) {
    if (string[i] != NULL) {
        printf("string[%d]: %s\n", i, strings[i]);
    }
}

In the first part, we allocate 3 poitners on the stack. And then, for every string we first compute the length, and then snprintf() into the successfuly allocated memory.

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