我可以在C中创建一个Char指针数组吗? [英] Can I create an Array of Char pointers in C?

查看:202
本文介绍了我可以在C中创建一个Char指针数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,C语言中的事物与我所学的任何其他语言都不同.在我的家庭作业中,我想创建一个指向chars数组的chars数组,但我不想拥有一个多维char数组,我想我将拥有更多控制权并创建char数组并将每个单独的数组放入索引中.原始字符数组:

I am new to C, and things are different in C than in any other language I've learned. In my homework I want to create an array of chars which point to an array of chars, but rather than make a multidimensional char array, I figure I'd have more control and create char arrays and put each individual one into the indexes of the original char array:

char keywords[10];
keywords[0] = "float";

上面的例子是为了澄清一个简单的例子.但是我的问题是由于我一直在做的研究,我对某些事情感到困惑.通常,这可以在其他语言中使用,但是在C语言中可以:

The above example is to clarify and a simple case. But my question is due to the research I've been doing, and I am confused about something. Normally this would work in other languages, but in C it would be:

char *keyword[10];
keywords[0] = "float";

但是当我想通过函数发送它时,为什么这样做是必要的:

But when I want to send it through a function, why is this necessary:

void function(char **keyword); //function prototype

仅仅传递数组指针还不够吗?

Wouldn't just passing the array pointer be enough?

推荐答案

您似乎对

void function(char ** keyword);

双星号只是表示此函数希望您将指针传递给char指针.该语法不包含有关您正在使用数组的事实,或者该char实际上是字符串中许多字符的第一个char的信息.作为程序员,您需要了解char **实际指向哪种数据结构.

The double stars just means that this function expects you to pass a pointer to a pointer to a char. This syntax doesn't include any information about the fact that you are using an array, or that the char is actually the first char of many in a string. It's up to you as the programmer to know what kind of data structure this char ** actually points to.

例如,假设数组的开头存储在地址0x1000处.该函数的keyword参数的值应为0x1000.如果取消引用keyword,则会获得数组中的第一个条目,它是一个char *,它指向字符串"float"中的第一个字符.如果取消引用char *,则会得到字符"f".

For example, let's suppose the beginning of your array is stored at address 0x1000. The keyword argument to the function should have a value of 0x1000. If you dereference keyword, you get the first entry in the array, which is a char * that points to the first char in the string "float". If you dereference the char *, you get the char "f".

(伪造的)代码如下:

void function(char **keyword)
{
    char * first_string = *keyword;   // *keyword is equivalent to keyword[0]
    char first_char = *first_string;  // *first_string is equivalent to first_string[0]
}

上面的示例中有两个指针.通过在取消引用之前在第一个指针上添加偏移量,可以访问数组中的不同字符串.通过在取消引用第二个指针之前向其添加偏移量,您可以访问字符串中的不同字符.

There were two pointers in the example above. By adding an offset to the first pointer before dereferencing it, you can access different strings in the array. By adding an offset to the second pointer before dereferencing it, you can access different chars in the string.

这篇关于我可以在C中创建一个Char指针数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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