在这个问题,有人建议意见,我应该不会投的结果malloc,即
int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
而不是:
int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
为什么会这样呢?
我一直对此感到好奇 - 为什么在C++中我必须从mallocC而不是在C中转换返回值?
以下是C++中的示例:
int *int_ptr = (int *)malloc(sizeof(int*));
Run Code Online (Sandbox Code Playgroud)
以下是C++中不起作用的示例(无转换):
int *int_ptr = malloc(sizeof(int*));
Run Code Online (Sandbox Code Playgroud)
我听说在C中,事实上,输出输出malloc()是一个错误.
任何人都可以评论这个话题吗?
所以我有一个std::string并且有一个函数可以接受char*并写入它.既然std::string::c_str()又std::string::data()回来了const char*,我不能用它们.所以我分配了一个临时缓冲区,用它调用一个函数并将其复制到std::string.
现在我计划处理大量信息,复制这个缓冲区会产生明显的影响,我想避免它.
有人建议使用&str.front()或&str[0]但是它会调用未定义的行为吗?
我有一个函数可以解析一些数据.我的问题是在使用strncpy后,当我尝试打印它时会得到一些垃圾.我尝试使用malloc使char数组具有确切的大小.
码:
void parse_data(char *unparsed_data)
{
char *temp_str;
char *pos;
char *pos2;
char *key;
char *data;
const char newline = '\n';
int timestamp = 0;
temp_str = (char*)malloc(strlen(unparsed_data));
g_print("\nThe original string is: \n%s\n",unparsed_data);
//Ignore the first two lines
pos = strchr(unparsed_data, newline);
strcpy(temp_str, pos+1);
pos = strchr(temp_str, newline);
strcpy(temp_str, pos+1);
//Split the line in two; The key name and the value
pos = strchr(temp_str, ':'); // ':' divides the name from the value
pos2 = strchr(temp_str, '\n'); //end of the …Run Code Online (Sandbox Code Playgroud)