5
I know arrays are static elements used when you have a predetermined size that you can use. But speaking of initialization, when the size is already set next to the array, I would like to know, essentially why you can’t use other types of arrays as you use strings in C (pointer notation). For example I can write:
#include <stdio.h>
int main(void)
{
char *sstring = "Olá, Mundo!";
char schars[] = {'O', 'l', 'a', '\0'};
int mnumbers[] = {1, 2, 3, 4, 5};
printf("Sstring : %s\n", sstring);
printf("Schars : %s\n", schars);
printf("Mnumber : %d\n", *mnumbers);
return 0;
}
But in return I cannot write:
char *sstring = "Olá, Mundo!";
char *schars = {'O', 'l', 'a', '\0'};
int *mnumbers = {1, 2, 3, 4, 5};
Even if the size is known, after all I am initiating the arrays. Why does this happen? Why, even in an array of chars initialized with parentheses, it is not possible to treat as pointers?
This occurs even with larger arrays and pointers (obviously):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int arrayInt[][3] = {{1, 2, 3}, {4, 5, 6}};
char *arrayChar[] = {"PALAVRA", "teste", "HEY"};
char **names = malloc(3 * sizeof(char *));
*names = "Teste";
*(names + 1) = "de";
*(names + 2) = "Arrays";
printf("%d\n", arrayInt[1][2]);
printf("%c\n", arrayChar[0][4]);
printf("Nome: %s %s %s\n", *names, *(names + 1), *(names + 2));
return 0;
}
It is not possible to do int **arrayInt = {{1, 2, 3}, {4, 5, 6}};
and it is still necessary to inform a dimension of the array, even stating it explicitly. A mixed form char *arrayChar[] = {"PALAVRA", "teste", "HEY"};
is still possible, but char *arrayChar[] = {{'O', 'l', 'a', '\0'}, {'M', 'u', 'n', 'd', 'o', '\0'}};
no. It seems that the use of brackets []
is connected to boot with keys {}
. I’d like to know why.
{ }
are key. Parentheses:( )
- but it’s probably just a confusion at the time of writing - almost a typo .– jsbueno
@jsbueno Obg. Fixed
– Rafael Bluhm