I have declare buffer const char* buf;
Later on I want to re assign size using memset
buffer_len = 1024;
memset(buf, '\0', buffer_len);
buf[strlen(buf)-1]='\0';
gives error:
client.cpp:73:30: error: invalid conversion from ‘const void*’ to ‘void*’ [-fpermissive]
In file included from client.cpp:2:0:
/usr/include/string.h:62:14: error: initializing argument 1 of ‘void* memset(void*, int, size_t)’ [-fpermissive]
client.cpp:75:21: error: assignment of read-only location ‘*(buf + (((sizetype)strlen(buf)) + -1u))’
I know it's due to const
but is there any alternative or way to perform it event it is const?
The assignment buf[strlen(buf)-1]='\\0';
is invalid because you defined buf
as const: const char* buf;
Read compiler's error message: error: assignment of read-only location
.
One point: You set buf
with nul \\0
so length of buf is 0
( \\0
at zero index) then if suppose you don't declare buf
as const even then you would be assiging at negative index because strlen(buf) - 1
== 0 - 1
= -1
– Undefined behaviour
memset
does not assign size. It fills a buffer with bytes. Filling a buffer declared as const char*
makes no sense, since the reason you declare it const is for yourself not to write to it.
You could create a different array instead, since this const
does not prevent you from changing the pointer itself.
Reassigning size should probably be called reallocating memory, you can use one of malloc
, calloc
or others to do it. Or since you've tagged this with c++, probably using the new
operator would be the best idea.
Obvious the author is asking a solution for what he want to operate. And simply explanation of the comping error is satisfactory. I do not want to explain why the author's code is not compiling, cause the above answers explain very well about this.
I am try to give a solution if the author really want to do all the operations he meant in his code, though I do not recommend to do that in real world software project.
Use const_cast to remove the const property of the variable:
const char* buf;
...
buffer_len = 1024;
...
char *ptr = const_cast<char *>(buf);
memset(ptr, '\0', buffer_len);
ptr[strlen(buf)-1]='\0';
A way to achieve flexible strings in C is to use realloc
:
//Get some malloc'ed strings.
char* myString = asprintf("my cool, malloc()-allocated string\n");
char* myOtherString = asprintf("Oh, and by the way: Hello World!\n");
//Make room in myString to append the other string.
size_t finalStringSize = strlen(myString) + strlen(myOtherString);
myString = realloc(myString, finalStringSize + 1); //+1 for termination
//Concatenate the strings
strcat(myString, myOtherString);
free(myOtherString), myOtherString = NULL;
But, of course, using C++ std::strings should be less of a hassle.
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.