0

私はバッファを宣言していますconst char* buf;

後で memset を使用してサイズを再割り当てしたい

buffer_len = 1024;
    memset(buf, '\0', buffer_len);
    buf[strlen(buf)-1]='\0';

エラーが発生します:

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))’

私はそれが原因であることを知ってconstいますが、それがconstであるイベントを実行するための代替手段または方法はありますか?

4

4 に答える 4

0

C で柔軟な文字列を実現する方法は、次を使用すること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;

しかし、もちろん、C++ の std::strings を使用することはそれほど面倒ではありません。

于 2013-08-24T08:04:59.817 に答える