Rya*_* Mc 0 c arrays pointers sizeof parameter-passing
我正在尝试编写一个打印给定数组元素的函数.但是,我不明白我如何计算传递给我的函数的数组元素.这是代码:
在这个例子中,我试图从我的函数中获取计数,尽管这只返回1.
#include <stdio.h>
void first_function(int ages[], char *names[]) {
int i = 0;
int count = sizeof(*ages) / sizeof(int);
for(i = 0; i < count; i++) {
printf("%s has lived %d years.\n", names[i], ages[i]);
}
}
int main(int argc, char *argv[])
{
int ages[] = { 7, 32, 36 };
char *names[] = {
"Tiger", "Sandy",
"Ryan"
};
first_function(ages, names);
printf("---\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我给函数一个额外的参数(count),然后从main中获取计数.这是正常的做法吗?看起来有点不洁净.
#include <stdio.h>
void first_function(int ages[], char *names[], int count) {
int i = 0;
for(i = 0; i < count; i++) {
printf("%s has lived %d years.\n", names[i], ages[i]);
}
}
int main(int argc, char *argv[])
{
int ages[] = { 7, 32, 36 };
char *names[] = {
"Tiger", "Sandy",
"Ryan"
};
int count = sizeof(ages) / sizeof(int);
first_function(ages, names, count);
printf("---\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你所谓的不洁方式是正常的方式.(sizeof如果数组参数已衰减为指针类型,则该惯用法不起作用).虽然考虑使用size_t计数类型,而不是int.
另一种方法是使用特定值来表示数组的结尾.实际上这就是字符串库函数在C中的工作方式; 用NUL发信号通知字符串的结尾.
根据C标准(6.7.6.3函数声明符(包括原型))
7 参数声明为''数组类型''应调整为''限定指向类型'',其中类型限定符(如果有)是在数组类型派生的[和]中指定的那些. ..
所以这个函数声明
void first_function(int ages[], char *names[]);
Run Code Online (Sandbox Code Playgroud)
调整声明为数组的相应参数后,等效于以下声明.
void first_function( int *ages, char **names );
Run Code Online (Sandbox Code Playgroud)
这是参数,ages并names在函数中有指针类型.结果这个表达
int count = sizeof(*ages) / sizeof(int);
Run Code Online (Sandbox Code Playgroud)
(我想你的意思是
int count = sizeof(ages) / sizeof(int);
^^^^
Run Code Online (Sandbox Code Playgroud)
尽管如此)
相当于
int count = sizeof( int) / sizeof(int);
Run Code Online (Sandbox Code Playgroud)
因为子表达式的类型*ages是int.
如果你要写表达式
int count = sizeof(ages) / sizeof(int);
Run Code Online (Sandbox Code Playgroud)
那相当于
int count = sizeof(int *) / sizeof(int);
Run Code Online (Sandbox Code Playgroud)
并且不会产生作为参数传递的数组的大小.
对于没有sentinel值的此类数组,如果需要,还必须将其大小传递给函数.
因此该函数应该声明为
void first_function(int ages[], char *names[], size_t n);
Run Code Online (Sandbox Code Playgroud)
并称之为
size_t count = sizeof(ages) / sizeof(*ages);
first_function(ages, names, count);
Run Code Online (Sandbox Code Playgroud)
注意不需要i在函数内初始化变量两次.功能可以看起来像
void first_function(int ages[], char *names[], size_t count)
{
for ( size_t i = 0; i < count; i++)
{
printf("%s has lived %d years.\n", names[i], ages[i]);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |