Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointers and arrays

I learned that:

char ar[] 

is the same of

char *ar

These three expressions:

char ar[][] //1
char *ar[] //2
char **ar //3

are the same thing for the compiler?

These two expressions:

char ar[]
char ar[][]

will allocate the array on the stack, while all the others will allocate it on the heap?

like image 752
AR89 Avatar asked Nov 30 '25 02:11

AR89


1 Answers

char ar[]; creates an array of characters when size is specified.

char * ar; creates a character pointer. Might point to even a single or more characters.

char ar[][]; when size is specified, creates a 2 dimensional array.
char *ar[]; creates an array of character pointers
char **ar; a pointer to pointer to character.

When you allocate memory statically such as

char a[10]; // this goes on stack

where as

char *a = malloc(10); // this goes on heap and needs to be freed by the programmer

A perhaps common thing could be that you allocated an array of arrays using a char **a i.e. each element of a is also a character array. Then any one element of this could be accessed using the syntax a[x][y]

Yet another difference is that char *a is a pointer variable i.e. a can be reassigned to another address where as char a[] would return a pointer constant and cannot be reassigned.

like image 104
fkl Avatar answered Dec 02 '25 15:12

fkl