Array Initialiser
These are the way to initialise an array
Using curly bracket
Can be use for any types
#include <stdio.h>
int main(void) {
char arr[] = {'a', 'b', 'c', '\0'};
char *ptr = arr;
printf("%c\n", ptr[1]); // 'b'
return 0;
}
An example for int
:
#include <stdio.h>
int main(void) {
int arr[] = {1,2,3,5,7};
int *ptr = arr;
printf("%d\n", ptr[1]); // 2
return 0;
}
Using double quotation
Double quotation only usable for char
array (string
)
#include <stdio.h>
int main(void) {
char *arr = "abcde";
char *ptr = arr;
printf("%c\n", ptr[1]); // b
return 0;
}
Using malloc
Similar for all data type
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *intArray = (int *) malloc(sizeof(int) * 5);
intArray2[0] = 1;
intArray2[1] = 2;
intArray2[2] = 3;
intArray2[3] = 4;
intArray2[4] = 5;
printf("%d\n", intArray[3]); // 4
return 0;
}