Sub: Update test_type

Body:

==== End ====
This commit is contained in:
Shockwave 2023-10-14 12:26:22 +08:00
parent dee5cb321b
commit 2a1edfd49b
2 changed files with 62 additions and 0 deletions

2
.gitignore vendored
View File

@ -14,6 +14,8 @@ _book
*.so *.so
*.swp *.swp
*.swo *.swo
*.bin
*.dat
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
**/__pycache__/ **/__pycache__/

View File

@ -1,6 +1,41 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
typedef struct {
long long id;
char name[40];
char title[100];
long long create_time;
} __attribute__((packed)) Person4;
/*
* struct
* __attribute__((packed))
*/
typedef struct {
long long id;
char name[40];
char title[100];
long long create_time;
} Person;
long long current_timestamp() {
long long tmp = 0;
struct timeval tval;
gettimeofday(&tval, NULL);
tmp = tval.tv_sec;
tmp = tmp * 1000;
tmp = tmp + tval.tv_usec / 1000;
return tmp;
}
int main(int argc, char **argv) { int main(int argc, char **argv) {
Person *p = NULL;
char *filename = "tmp.dat";
FILE *fp = fopen(filename, "w");
// there is no type of byte in c // there is no type of byte in c
// printf("Size of byte: %d bytes\n", sizeof(byte)); // printf("Size of byte: %d bytes\n", sizeof(byte));
printf("Size of char: %lu bytes\n", sizeof(char)); printf("Size of char: %lu bytes\n", sizeof(char));
@ -25,5 +60,30 @@ int main(int argc, char **argv) {
* Size of double: 8 bytes * Size of double: 8 bytes
* Size of long double: 16 bytes * Size of long double: 16 bytes
*/ */
long size_p = sizeof(Person);
long size_p4 = sizeof(Person4);
/* 取消优化后 Person4 的大小为 156 bytes优化的 Person 大小为 160 bytes */
printf("Size of Person: %ld, Size of Person4: %ld\n", size_p, size_p4);
p = (Person *)malloc(size_p);
memset(p, 0, size_p);
p->id = 1L;
strcpy(p->name, "小明");
strcpy(p->title, "宇宙无敌暴龙战神");
p->create_time = current_timestamp();
char *buf = (char *)p;
fwrite(buf, sizeof(char), size_p, fp);
fclose(fp);
fp = fopen(filename, "r");
char *buf_read = (char *)malloc(size_p);
fread(buf_read, sizeof(char), size_p, fp);
Person *q = (Person *)buf_read;
printf("Person q, size: %ld bytes, id: %lld, name: %s, title: %s, create_time: %lld\n",
size_p, q->id, q->name, q->title, q->create_time);
fclose(fp);
free(p);
return 0; return 0;
} }