notes/snippet/cpp/test_static.c

48 lines
1.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
typedef struct {
long long id;
char *name;
char *desc;
int age;
} Person;
void test () {
static int num = 0;
num++;
printf("Function test has been called %d times\n", num);
}
void test2() {
// static variables defined in fuction can only be visited by this function.
static int num = 0;
num++;
printf("Function test2 has been called %d times\n", num);
}
int main(int argc, char **argv) {
// p is on stack, while q is on heap
Person p;
Person *q = (Person *)malloc(sizeof(Person));
if (q == NULL) {
printf("malloc fails\n");
return -1;
}
// test();
// test();
// test2();
// test2();
/**
* TODO: 看起来操作系统决定 malloc 申请的内存在哪里
* Output on linux64 compiled by clang
* addr of p: 0x5619048df2d0, addr of q: 0x7fb51f2e19e0
* Output on win64 compiled by MinGW64 gcc
* addr of p: 000000B0591FFB20, addr of q: 000000B0591FFB00
*/
printf("addr of p: %p, addr of q: %p\n", p, *q);
free(q);
return 0;
}