如何测试指针数组的结尾?

#include  int main(void) { char *t[10]={"Program", "hjl","juyy"}; int i; //printf("%c \n",*t[3]); int ch=*t[0]; for(i=0;*t[i]!='\0';i++){ printf("%d",i); } return 0; } 

该计划在一段时间内停止了工作。 任何人都可以解释原因吗?

不太确定你想要什么输出,但可能你想输出数组中的字符串。

您无法直接检测到数组的结尾。

您需要在数组末尾放置一个sentinel值,例如NULL

 #include  int main(void) { char *t[10] = { "Program", "hjl", "juyy", NULL }; //^sentinel value int i; for (i = 0; t[i] != NULL; i++) { printf("%d: %s\n", i, t[i]); } return 0; } 

或者你需要计算元素的数量,但这只有在你的t数组的初始化列表的数字元素与数组的长度相同时才有效,这在你的代码中并非如此:

 #include  int main(void) { char *t[] = { "Program", "hjl", "juyy"}; // ^ no size here means that the array will have // the size of the initalizer list (3 here), int i; for (i = 0; i < sizeof(t)/sizeof(t[0]); i++) { printf("%d: %s\n", i, t[i]); } return 0; } 

sizeof(t)t数组的大小(以字节为单位)。 sizeof(t[0])t的第一个元素的大小,这里是sizeof(char*) (指针的大小)。

因此sizeof(t)/sizeof(t[0])t数组的元素数(这里是3)。

两个版本的输出将是:

0:程序
1:hjl
2:juyy

如果我已正确理解您要输出的内容,则程序可以按以下方式查看。

 #include  int main(void) { char *t[10] = { "Program", "hjl", "juyy" }; for ( char **p = t; *p; ++p ) { for ( char *q = *p; *q; ++q ) printf( "%d ", ( unsigned char )*q ); putchar( '\n' ); } return 0; } 

它的输出是

 80 114 111 103 114 97 109 104 106 108 106 117 121 121 

由于数组被声明为具有10个元素并且仅使用三个初始化器显式初始化,因此数组的所有其他元素都由零初始化。 您可以将此事实用作循环的条件。

像这样定义数组:

 char *s[] = { "text 1 ...", "text 2 ...", "text 3 ...", NULL }; 

实现函数来确定这样的元素数量:

 #include  ssize_t number_of_elements(const char ** p) { ssize_t e = -1; /* Be pessimistic. */ if (NULL == p) { errno = EINVAL; } else { char * t = p; while (NULL != *t) { ++t; } e = (ssize_t) (t - p); } return e; } 

这样叫:

 #include  #include  ssize_t number_of_elements(const char ** p) int main(void) { int ec = EXIT_SUCCESS; ssize_t e; if (-1 == (e = number_of_elements(s))) { ec = EXIT_FAILURE; perror("number_of_elements() failed"); } else { prints("s has %zd elements.\n", e); } return ec; }