如何评估(int*)%int?

Soh*_*abi -4 c

我正在实现一个循环队列,当队列已满时,我希望指针返回到数组地址的第一个.

struct Sample{

    void* ptr;
};

int main() {

    char a[20] = "hello";

    struct Sample sample;

    sample.ptr = (a + 2) % 6;

    printf("%s\n", sample.ptr);

}
Run Code Online (Sandbox Code Playgroud)

当我编译代码时,我收到以下错误:

invalid operands to binary % (have ’char* ’ and ‘int’)

我知道问题来自%,例如,如果我将第12行更改为sample.ptr = (a + 2)它将起作用.但我需要评估%.我怎样才能做到这一点?

Dan*_*_ds 5

sample.ptr = (a + 2) % 6;
Run Code Online (Sandbox Code Playgroud)

a是一个char*(即一个内存地址),添加2就可以了 - 这将chars在内存中进一步指向2 .

但做一个%(模数)(即使它工作)当然会创建一个无效的指针.

sample.ptr将指向内存地址0到5(0为NULL pointer),这可能不是你想要的.

更新:

我正在实现一个循环队列,当队列已满时,我希望指针返回到数组地址的第一个

要实现循环队列,您可以使用:

sample.ptr = a + (pos % number_of_items_in_array); // brackets not really needed
Run Code Online (Sandbox Code Playgroud)

要么:

sample.ptr = &a[pos % number_of_items_in_array];
Run Code Online (Sandbox Code Playgroud)

sample.ptr也应该是a char*,而不是void*:

struct Sample{
    char* ptr;
};
Run Code Online (Sandbox Code Playgroud)