小编Ale*_*lex的帖子

为什么指向一个超出有效对象的位置对于指针来说是可以接受的?

在 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 pointers

5
推荐指数
1
解决办法
151
查看次数

使用迭代器之间的比较来遍历std :: map

当我想用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++ dictionary iterator traversal

4
推荐指数
1
解决办法
80
查看次数

strtok() 与 realloc() 奇怪的行为

我有以下用 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() 表现出奇怪的行为,它返回一个词,该词不存在于 …

c strtok realloc

0
推荐指数
1
解决办法
104
查看次数

标签 统计

c ×2

c++ ×1

dictionary ×1

iterator ×1

pointers ×1

realloc ×1

strtok ×1

traversal ×1