what\'s the difference between these 2 declarations:
char (*ptr)[N];
vs.
char ptr[][N];
thanks.
(1) declaration
char (*ptr)[N];
ptr
is pointer to char array of size N
following code will help you to on how to use it:
#include
#define N 10
int main(){
char array[N] = "yourname?";
char (*ptr)[N] = &array;
int i=0;
while((*ptr)[i])
printf("%c",(*ptr)[i++]);
}
output:
yourname?
See: Codepad
(2.A)
Where as char ptr[][N];
is an invalid expression gives error: array size missing in 'ptr'
.
But char ptr[][2] = {2,3,4,5};
is a valid declaration that is 2D char array. Below example:
int ptr[][3] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
Create an int array of 3 rows and 5 cols. Codepade-Example
(2.B) Special case of a function parameter!
As function parameter char ptr[][N];
is a valid expression. that means ptr
can point a 2D char array of N columns
.
example: Read comments in output
#include
int fun(char arr[][5]){
printf("sizeof arr is %d bytes\n", (int)sizeof arr);
}
int main(void) {
char arr[][6] = {{'a','b'}, {'c','d'}, {'d','e'}};
printf("sizeof arr is %d bytes\n", (int)sizeof arr);
printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
fun(arr);
return 0;
}
output:
sizeof arr is 6 bytes // 6 byte an Array 2*3 = 6
number of elements: 3 // 3 rows
sizeof arr is 4 bytes // pointer of char 4 bytes
To view this example running: codepad