是 C while pointer going to work with any pointer variable
Is C while pointer going to work with any pointer variable
我知道通常的 while (*pointer)
用例是使用字符串。
char str[]= "string";
int i = 0;
while (*(str + i++));
当取消引用的字符为 [=13=]
.
时,循环结束
但是,我有这段代码可以递归地打印出字符串数组。
void print_array(char** arr, bool printComma) {
if (*arr) {
if (printComma) {
printf(", ");
}
printf("%s", *arr);
print_array(arr + 1, true);
}
}
int main(int argc, char **argv) {
print_array(argv, false);
}
它按预期工作并打印出 char **arr
中的字符串。
但是,我不明白系统如何知道数组的末尾,因为取消对指针的引用将给出一个指向内存的值,我也不确定该值是多少。
此外,如果我将此样式与任何指针变量一起使用,是否保证循环结束?
之所以有效,是因为传递给 the main
function 的 argv
数组由 NULL
指针终止。
即argv[argc]
保证为NULL
.
和NULL
指针在用作条件时被认为是false
。例如 if (*arr)
根据C标准*5.1.2.2.1程序启动)
2 If they are declared, the parameters to the main function shall obey
the following constraints:
— The value of argc shall be nonnegative.
— argv[argc] shall be a null pointer
所以在这个 if 语句中
if (*arr) {
检查下一个指针*arr
(类型char *
)是否等于NULL
。
为了更清楚地考虑以下演示程序,其中使用类似定义的数组代替命令行参数。
#include <stdio.h>
void print_array( char **arr )
{
*arr == NULL ? ( void )putchar( '\n' ) : ( printf( "%s", *arr ), print_array( arr + 1 ) );
}
int main(void)
{
char *s[] =
{
"Hello", " ", "World!", NULL
};
print_array( s );
return 0;
}
程序输出为
Hello World!
我知道通常的 while (*pointer)
用例是使用字符串。
char str[]= "string";
int i = 0;
while (*(str + i++));
当取消引用的字符为 [=13=]
.
但是,我有这段代码可以递归地打印出字符串数组。
void print_array(char** arr, bool printComma) {
if (*arr) {
if (printComma) {
printf(", ");
}
printf("%s", *arr);
print_array(arr + 1, true);
}
}
int main(int argc, char **argv) {
print_array(argv, false);
}
它按预期工作并打印出 char **arr
中的字符串。
但是,我不明白系统如何知道数组的末尾,因为取消对指针的引用将给出一个指向内存的值,我也不确定该值是多少。
此外,如果我将此样式与任何指针变量一起使用,是否保证循环结束?
之所以有效,是因为传递给 the main
function 的 argv
数组由 NULL
指针终止。
即argv[argc]
保证为NULL
.
和NULL
指针在用作条件时被认为是false
。例如 if (*arr)
根据C标准*5.1.2.2.1程序启动)
2 If they are declared, the parameters to the main function shall obey the following constraints:
— The value of argc shall be nonnegative.
— argv[argc] shall be a null pointer
所以在这个 if 语句中
if (*arr) {
检查下一个指针*arr
(类型char *
)是否等于NULL
。
为了更清楚地考虑以下演示程序,其中使用类似定义的数组代替命令行参数。
#include <stdio.h>
void print_array( char **arr )
{
*arr == NULL ? ( void )putchar( '\n' ) : ( printf( "%s", *arr ), print_array( arr + 1 ) );
}
int main(void)
{
char *s[] =
{
"Hello", " ", "World!", NULL
};
print_array( s );
return 0;
}
程序输出为
Hello World!