What is the difference between the following declarations in C?

what is the difference between these two ads:

char (*ptr)[N]; 

vs.

 char ptr[][N]; 

thanks.

+2
source share
4 answers

(1) Announcement

 char (*ptr)[N]; 

ptr - pointer to char array of size N The following code will help you in using:

 #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 char ptr[][N]; - invalid expression, gives an error: array size missing in 'ptr' .

But char ptr[][2] = {2,3,4,5}; is a valid declaration, which is a 2D char array. Below is an 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 columns. Code Example

(2.B) Special case of function parameter!

As a functional parameter char ptr[][N]; is a valid expression. this means ptr can indicate a 2D char array of N columns .

example: reading comments on 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: codepad

+4
source

First declare ptr as a pointer to an array N of char
The second is to declare ptr as an array of array N from char

Plz link link

+2
source

The first declares a pointer to an N-long array, the other declares two dinemsional arrays. Note. They can be used to achieve similar functionality, but they do not mean the same!

+1
source

1.ptr - a pointer to an array of characters of size N 2. ptr looks like a two-dimensional array, but the number of lines is not provided. In a two-dimensional array, both the number of rows and columns is mandatory, since the compiler will determine how many bytes should be assigned to the array (number of rows * number of columns * size of data). This ad may work fine, as shown below:

 char[][2]={ {'a','b'} }; 

since here the compiler will look and understand that there is one line. If a two-dimensional array is passed as an argument to the function, the number of columns (second dimension) must be provided by enforcement, passing the number of rows not required in the function definition.

0
source

Source: https://habr.com/ru/post/1490418/


All Articles