Sub: add cpp snippets

Body:

==== End ====
This commit is contained in:
Shockwave 2023-09-29 09:10:45 +08:00
parent c23e655e05
commit 44d6e2f076
2 changed files with 38 additions and 5 deletions

View File

@ -1,4 +1,12 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct {
long long id;
char *name;
char *desc;
int age;
} Person;
void test () {
static int num = 0;
@ -7,14 +15,26 @@ void test () {
}
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) {
test();
test();
test2();
test2();
// 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);
}

13
snippet/cpp/test_type.c Normal file
View File

@ -0,0 +1,13 @@
#include <stdio.h>
int main(int argc, char **argv) {
// there is no type of byte in c
// printf("Size of byte: %d bytes\n", sizeof(byte));
printf("Size of char: %lu bytes\n", sizeof(char));
printf("Size of short: %lu bytes\n", sizeof(short));
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of long: %lu bytes\n", sizeof(long));
printf("Size of long int: %lu bytes\n", sizeof(long int));
printf("Size of long long: %lu bytes\n", sizeof(long long));
return 0;
}