C/C++ can't figure out pointers or arrays? Explain struct size with sizeof!

array? pointer?

I heard that C++ plans to abandon the pointer, who makes the pointer so difficult!

my environment:

>uname -a
CYGWIN_NT-10.0-WOW DESKTOP-499IG24 2.10.0(0.325/5/3) 2018-02-02 15:21 i686 Cygwin

It can be seen that it is a 32bit kernel, that is, the sizeof of the space occupied by the pointer is 4.

Then this program:

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

/*main function*/
int main(int argc, char**argv)
{
    char s1[] = "abcdefg";
    char s2[] = {'a','b','c','d','e','f','g'};
    char s3[] = {"abcdefg"};
    char *s4 = "abcdefg";
    //char *s5 = {'a','b','c','d','e','f','g'};//error
    char *s6 = {"abcdefg"};
    
    printf("s:%s, length:%2d, sizeof:%2d\n",s1,strlen(s1),sizeof(s1));
    printf("s:%s, length:%2d, sizeof:%2d\n",s2,strlen(s2),sizeof(s2));
    printf("s:%s, length:%2d, sizeof:%2d\n",s3,strlen(s3),sizeof(s3));
    printf("s:%s, length:%2d, sizeof:%2d\n",s4,strlen(s4),sizeof(s4));
    //printf("s:%s, length:%2d, sizeof:%2d\n",s5,strlen(s5),sizeof(s5));//error
    printf("s:%s, length:%2d, sizeof:%2d\n",s6,strlen(s6),sizeof(s6));
    
    s1 [0] = 'z';
    s2 [0] = 'z';
    s3 [0] = 'z';
    //s4[0] = 'z';//error
    //s5[0] = 'z';//error
    //s6[0] = 'z';//error
    
    return 1;
}

The output is:

>gcc string.c
>a.exe
s:abcdefg, length: 7, sizeof: 8
s:abcdefgabcdefg, length:14, sizeof: 7
s:abcdefg, length: 7, sizeof: 8
s:abcdefg, length: 7, sizeof: 4
s:abcdefg, length: 7, sizeof: 4

So why are these sizeofs different?

The size of the pointer of the 32bit system kernel is 4, the next two 4 are not difficult to explain, the above two 8 can be interpreted as automatic completion (similar to struct, struct is filled according to the maximum number of bytes), and the size is 7 is the corresponding array.

sizeof(struct)

The following procedures are used to print:

printf("%d+%d+%d+%d = %d\n",
        sizeof(int),sizeof(char),sizeof(float),sizeof(double),sizeof(S));

What needs to be understood is the automatic alignment mechanism of struct:

Example 1:

struct{
    int a;
    char ch;
    float f;
    double d;
}S;

The output is:

>gcc string.c
>a.exe
4+1+4+8 = 24


Example 2:

struct{
    int a;
    char ch;
    float f;
}S;

result:

>gcc string.c
>a.exe
4+1+4+8 = 12


Example 3:

struct{
    float f;
    double d;
}S;

result:

>gcc string.c
>a.exe
4+1+4+8 = 16


Example 4:

struct{
    int a;
    double d;
}S;

result:

>gcc string.c
>a.exe
4+1+4+8 = 16



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326486748&siteId=291194637