C中以下声明之间有什么区别? [英] 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];
谢谢.
推荐答案
(1)声明
char (*ptr)[N];
ptr
是pointer to char array of size 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++]);
}
输出:
yourname?
请参阅:数字键盘
(2.A)
如果char ptr[][N];
是无效表达式,则会出现错误:array size missing in 'ptr'
.
Where as char ptr[][N];
is an invalid expression gives error: array size missing in 'ptr'
.
但是char ptr[][2] = {2,3,4,5};
是2D char数组的有效声明.下面的示例:
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}};
创建一个3行5列的 int数组. Codepade-示例
Create an int array of 3 rows and 5 cols. Codepade-Example
(2.B)函数参数的特例!
作为函数参数char ptr[][N];
是有效的表达式.这意味着ptr
可以指向2D char array of N columns
.
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;
}
输出:
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
这篇关于C中以下声明之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!