How to initialize variables in c
Initializing is not complex but something different for various languages. It makes me tired to remember if I start to use another language from time to time. Recently I’m interested in python, javascript. There is no problem in using these languages, but it is confused to use previous languages. This code snippets can help reduce my stress.
Integer array
We usually initialize array with for loop.
for (idx=0 ; idx < sizeof(arr)/sizeof(int) ; idx++)
{
arr[idx] = 0;
}
Instead, we can also initialize array with memset to set 0.
#include <stdio.h>
int main(int argc, char *argv[])
{
int idx = 0;
int arr[5] = {1,2,3,};
printf("sizeof : [%d][%d]", sizeof(arr), sizeof(int));
printf("--------------------\n");
for (idx=0 ; idx < sizeof(arr)/sizeof(int) ; idx++)
{
printf("init. size[%d]: %d\n", idx, arr[idx]);
}
printf("--------------------\n");
memset(arr, 0x00, sizeof(arr));
for (idx=0 ; idx < sizeof(arr)/sizeof(int) ; idx++)
{
printf("memset size[%d]: %d\n", idx, arr[idx]);
}
}
Result
sizeof : [20][4]
--------------------
init. size[0]: 1
init. size[1]: 2
init. size[2]: 3
init. size[3]: 0
init. size[4]: 0
--------------------
memset size[0]: 0
memset size[1]: 0
memset size[2]: 0
memset size[3]: 0
memset size[4]: 0
typedef struct _TEST {
char aa[2];
char bb[3];
} TEST;
TEST *tst[100];
printf("size: %d %d %d\n", sizeof(tst), sizeof(&tst[0]), sizeof(&tst[0][0]));
size: 800 8 8
Leave a comment