notes/snippet/cpp/test_static.c

41 lines
851 B
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();
// addr of p: 0x5619048df2d0, addr of q: 0x7fb51f2e19e0
printf("addr of p: %p, addr of q: %p\n", p, *q);
free(q);
}