[英]What is the difference between the following declarations in C?
what's the difference between these 2 declarations: 这两个声明之间的区别是什么:
char (*ptr)[N];
vs. 与
char ptr[][N];
thanks. 谢谢。
(1) declaration (1)声明
char (*ptr)[N];
ptr
is pointer to char array of size N
following code will help you to on how to use it: ptr
是pointer to char array of size N
下面的代码将帮助您了解如何使用它:
#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?
(2.A) (2.A)
Where as char ptr[][N];
其中以
char ptr[][N];
is an invalid expression gives error: array size missing in 'ptr'
. 是无效的表达式会给出错误:
array size missing in 'ptr'
。
But char ptr[][2] = {2,3,4,5};
但是
char ptr[][2] = {2,3,4,5};
is a valid declaration that is 2D char array. 是2D char数组的有效声明。 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 . 创建一个3行5列的整数数组 。 Codepade-Example
Codepade-实施例
(2.B) Special case of a function parameter! (2.B)功能参数的特例!
As function parameter char ptr[][N];
作为函数参数
char ptr[][N];
is a valid expression. 是一个有效的表达。 that means
ptr
can point a 2D char array of N columns
. 这意味着
ptr
可以指向2D char array of N columns
的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
The first declares a pointer to an N-long array, the other declares an two dinemsional array. 第一个声明一个指向N长数组的指针,另一个声明一个两个二维数组。 Note: They can be used to achieve the similar functionality, but they don't mean the same!
注意:它们可用于实现类似的功能,但并不意味着相同!
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: 1.ptr是指向大小为N的字符数组的指针。2.ptr看起来像一个二维数组,但未提供行数。在二维数组中,行数和列数都是强制性的,因为编译器将决定应保留多少字节分配给数组by(行数*列数*数据类型的大小)。此声明可以正常工作如下:
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. 如此处的编译器将查找并理解有一行。或者当将二维数组作为函数参数传递时,必须通过强制提供列数(第二维),函数中传递的行数不是强制性的定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.