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<stdio.h>
#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 <stdio.h>
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
First is declare ptr as pointer to array N of char
Second is declare ptr as array of array N of char
Plz refer link
1.ptr is pointer to character array of size N 2. ptr looks like a double dimensional array but number of rows is not provided.In 2-D array both number of rows and column is compulsory as compiler will decide how many bytes should be assigned to array by (number of row*number of column*size of data type).This declaration may work fine as below:
char[][2]={
{'a','b'}
};
as here compiler will look and understand that there is one row.or when a two dimensional array is passed on as a function argument,the number of columns(second dimension) must be provided by compulsion,passing number of rows is not compulsory in function definition.
The first declares a pointer to an N-long array, the other declares an two dinemsional array. Note: They can be used to achieve the similar functionality, but they don't mean the same!