在C中如何获取指向字符字符串的指针数组中的项目数 [英] In C how to get number of items in array of pointers to char strings

查看:50
本文介绍了在C中如何获取指向字符字符串的指针数组中的项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现以下函数来打印通过指针数组引用的几个 char 字符串的内容.如何在不将总数作为函数参数传递的情况下确定有多少个指针?

I want to implement the following function to print the contents of several char strings which are referenced through a pointer array. How can I determine how many pointers there are without passing the total as an argument of the function?

如果它是一个 int 类型的数组,那么可以使用 sizeof() 函数,但鉴于我的数组的每个项目都是一个指向char 字符串,每个字符串的长度可能不同,我认为我不能使用这种方法.

If it was an array of type int then it would be possible to use the sizeof() function but given that each item of my array is a pointer to a char string and each string could be of different length I don't think I can use this approach.

void printCharArray(char *arr[]){

    int length = sizeof(arr) / sizeof(char); /* this does not give correct 
                                          number of items in the pointer array */

    for (int i=1;i<=length; i++) {
        printf("Array item: [%s]",arr[i]);
    }

}

推荐答案

没有内置的方法可以做到这一点,因为 C 不会像这样为您跟踪数组中的元素数量.

There is no built-in way to do this as C does not track the number of elements in an array for you like this.

您有几个选择:

  1. 传递数组中的项目数.
  2. 将最后一项设置为 NULL,以便代码知道何时到达末尾.(这就是 C 字符串的处理方式.)
  3. 否则修改您的数据结构以跟踪数组中的项目数.

这篇关于在C中如何获取指向字符字符串的指针数组中的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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