在C语言中如何让指针为char字符串数组项目数 [英] In C how to get number of items in array of pointers to char strings

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

问题描述

我要实现以下功能打印它们通过一个指针数组引用数字符字符串的内容。我怎么能确定没有传球总作为函数的参数有多少指针存在?

如果它是类型的数组 INT 那么就可以使用的sizeof()的功能,但因为我的数组中的每个产品的指针,字符字符串,每个字符串可以有不同的长度,我不认为我可以使用这种方法。

 无效printCharArray(字符* ARR []){    INT长度= sizeof的(ARR)/的sizeof(字符); / *这不给予纠正
                                          指针数组中的项数* /    的for(int i = 1; I< =长度;我++){
        的printf(阵列项目:[%S],编曲[I]);
    }}


解决方案

有没有内置的方式做到这一点为C不跟踪在这样一个数组为你的元素个数。

您有几个选项:


  1. 传递的项目数阵列中

  2. 设置的最后一项为NULL,所以当它到达终点的code知道。 (这是一种C字符串的处理方式。)

  3. 否则修改数据结构以跟踪在阵列中的项目的数目。

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?

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

}

解决方案

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.

You have a couple of options:

  1. Pass the number of items in the array.
  2. Set the last item to NULL so the code knows when it's reached the end. (This is kind of how C strings are handled.)
  3. Otherwise modify your data structures to track the number of items in the array.

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

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