kanhongj
V2EX  ›  问与答

请教 c/c++ sizeof() struct 的一个 问题

  •  
  •   kanhongj · Jul 3, 2022 · 1748 views
    This topic created in 1437 days ago, the information mentioned may be changed or developed.
    #include <stdio.h>
    #include <stdlib.h>
    
    struct A{
    	int a;
            char b;
    };
    
    int main(){
    	A *ptrA;
        
            printf("%lu\n", sizeof(*ptrA));
    	printf("%lu\n", sizeof(A))
    	return 0;
    }
    
    

    请问这两个得出来的值都为 8 ;为什么,我不理解 *ptrA 为啥也是 8 ,不是没有申请内存吗?

    3 replies    2022-07-03 23:44:25 +08:00
    lifanxi
        1
    lifanxi  
       Jul 3, 2022
    sizeof 后面本质上跟的是个类型。如果是变量,那就是这个变量对应的类型,而不是这个变量本身。
    所以不管有没有分配内存,返回的都是类型的大小。
    thedrwu
        2
    thedrwu  
       Jul 3, 2022 via Android   ❤️ 4
    还没领身份证你也能知道身份证号码有几位
    kanhongj
        3
    kanhongj  
    OP
       Jul 3, 2022
    哦哦哦,悟了悟了,明白了,有点到思维胡同了,哈哈哈,谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2781 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 15:31 · PVG 23:31 · LAX 08:31 · JFK 11:31
    ♥ Do have faith in what you're doing.