小编Oma*_*ñoz的帖子

为什么*pp [0]等于**pp

所以我试图找出指针,我读了一些关于指针指针的帖子,但我仍然无法弄清楚为什么这个程序运行没有问题

#include <stdio.h>
#include <assert.h>

int main(){
    char* p = "abc";

    char** pp[2];
    pp[0] = &p;
    assert(*pp[0]==**pp);

    printf("Comparison: %s, %s\n",**pp, *pp[0]);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

据我所知,内存看起来像这样

Memory Address (hex)    Variable name    Contents
1000                                     'a' == 97 (ASCII)
1001                                     'b' == 98
1002                                     'c' == 99
1003                                     0
...
2000-2003               p                1000 hex
...
3000-3003               pp[0]            2000 hex
Run Code Online (Sandbox Code Playgroud)

在这一点上假设我记忆正确...我希望*pp [0]进入记忆并说......

所以pp [0]指向p的地址,即0x2000,通过解除引用,我希望得到地址0x2000的内容,在我的观点中意味着我会得到0x1000,但事实并非如此该计划的输出是:

OUTPUT

abc, abc
Run Code Online (Sandbox Code Playgroud)

在**pp的情况下,我认为它首先取消引用pp,这将给我们任何pp指向的内容,这意味着0x2000的内容(这是0x1000)然后通过再解除引用我们得到地址0x1000的内容

为什么他们会平等?我在哪里错过了什么

c pointers dereference

3
推荐指数
1
解决办法
634
查看次数

puts()显示strcpy的全部内容,即使发生dest溢出

创建一个大小为5的char数组后,我strcpy用来填充数组的内容,但是字符串大于原始大小; 然后我puts()用来显示数组的内容,显示整个字符串,这是奇怪的,因为我遍历数组内容,我觉得内容不存储在内存中(但显示它们).这是我正在测试的代码

#include <stdio.h>
#include <string.h>

int main(){
    char str1[5];
    int i = 0;

    strcpy(str1,"Hello world");

    puts(str1);
    printf("Size of str1: %d\n",sizeof(str1));

    for(i = 0;i < 15; i++){
            printf("%c",str1[i]);
    }
    puts(""); // Blank space
    puts(str1); // Display contents again... Different result!
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Hello world
Size of str1: 5
Hello   ld  [
Hello
Run Code Online (Sandbox Code Playgroud)

输出中的第3行是内存中的实际内容(我进一步迭代验证).

我不希望第一个puts(str1)显示整个短语,但它确实显示我重复的内容puts(str1)和输出更改,这对我来说似乎是随机的,数组大小也只有5.

你能帮我弄清楚发生了什么吗?

c arrays strcpy

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

标签 统计

c ×2

arrays ×1

dereference ×1

pointers ×1

strcpy ×1