如何测试指针数组的结尾? [英] How to test for the end of a pointer array?

查看:117
本文介绍了如何测试指针数组的结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

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;
}

程序在一段时间内停止工作.有人可以解释原因吗?

The program stopped working in some time. Can anyone please explain the reason?

推荐答案

不太清楚所需的输出,但是可能要在数组中输出字符串.

Not quite sure what output you want, but probably you want to output the strings in the array.

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

You can't detect the end of an array directly.

您要么需要在数组的末尾放置一个哨兵值,例如NULL:

You either need to put a sentinel value at the end of the array, for example NULL:

#include <stdio.h>

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数组的初始化程序列表的元素数量与数组的长度相同时才有效,而在代码中则不是这种情况:

or you need tot count the number of elements, but this works only if the number elements of the initializer list of your t array is the same as the length of the array, which is not the case in your code:

#include <stdio.h>

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) is the size of the t array in bytes. sizeof(t[0]) is the size of the first element of t, which is here sizeof(char*) (size of a pointer).

因此,sizeof(t)/sizeof(t[0])t数组的元素数(此处为3).

Therefore sizeof(t)/sizeof(t[0]) is the number of elements of the t array (3 here).

两个版本的输出将是:

0:程序
1:hjl
2:juyy

0: Program
1: hjl
2: juyy

这篇关于如何测试指针数组的结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆