在 Jens Gustedt 的教科书“现代 C”中,我读到了“指针必须指向有效对象或超出有效对象的一个位置或为空”的指针。为什么指向一个有效对象之外的位置是可以接受的?例如:
int array[5] = {0};
int* p = array;
p = array + 5 // points to a valid location
p = array + 6 // points to an invalid location
Run Code Online (Sandbox Code Playgroud) 当我想用C++遍历地图时,我们可以使用以下技术:
for (auto i = m.begin(); i != m.end(); i++)
{ ... ... }
Run Code Online (Sandbox Code Playgroud)
为什么我们不能使用以下代码:
for (auto i = m.begin(); i < m.end(); i++)
{ ... ... }
Run Code Online (Sandbox Code Playgroud)
我的猜测是因为关联容器中的元素不像顺序容器那样按顺序存储,是吗?
我有以下用 C 编写的程序:
...
char *answer = NULL;
char *pch = strtok(phrase, " "); // phrase is a string with possibly many words
while (pch) {
char *tmp = translate_word(pch); // returns a string based on pch
void *ptr = realloc(answer, sizeof(answer) + sizeof(tmp) + 1000); // allocate space to answer
if (!ptr) // If realloc fails
return -1;
strcat(answer, tmp); // append tmp to answer
pch = strtok(NULL, " "); // find next word
}
...
Run Code Online (Sandbox Code Playgroud)
问题是 strtok() 表现出奇怪的行为,它返回一个词,该词不存在于 …