[英]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. 我是C语言的新手。我拥有这种类型的代码,当我尝试执行该代码时,出现了以下警告消息:“传递'snprintf'的参数1会从指针目标类型中丢弃'const'限定符”,并且没有任何反应。
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]
. 试图写入
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. 但是在这里,它甚至更加严重:
strings[i]
没有为字符串甚至指针(!)分配任何内存,因此删除const
限定符将在运行程序时导致未定义的行为。
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. 在第一部分中,我们在堆栈上分配3个Poitner。 And then, for every string we first compute the length, and then
snprintf()
into the successfuly allocated memory. 然后,对于每个字符串,我们首先计算长度,然后将
snprintf()
放入成功分配的内存中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.