C语言 在 C 中创建一个数组来保存字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16091848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:04:53  来源:igfitidea点击:

Making an Array to Hold Arrays of Character Arrays in C

carrayscharacter-arrays

提问by Dae314

My C is a little more than rusty at the moment, so I'm failing to create something I think should be pretty basic.

我的 C 目前还有些生疏,所以我没有创造出我认为应该非常基本的东西。

Allow me to refer to character arrays as strings for this post. It will make things clearer for both me and you.

在这篇文章中,请允许我将字符数组称为字符串。这将使我和你的事情变得更加清晰。

What I have is an array that can hold 1 or more strings. For instance {"ab", "cd", "ef"}. I want to make another array to store multiple versions of the array of strings. So something like {{"ab", "cd", "ef"}, {"gh", "ij"}, {"kl"}}.

我拥有的是一个可以容纳 1 个或多个字符串的数组。例如 {"ab", "cd", "ef"}。我想制作另一个数组来存储字符串数组的多个版本。所以像 {{"ab", "cd", "ef"}, {"gh", "ij"}, {"kl"}}。

What I have right now is:

我现在拥有的是:

char *arrayOfStrings[50]; // a single array to hold multiple strings
char **arrayOfArraysOfStrings[10]; // array to hold multiple snapshots of arrayOfStrings

The array of strings changes over time and I'm using the array of arrays of strings to basically hold historical snapshots of arrayOfStrings. My problem comes when I need to access the snapshot array for data. This is the code I have to put stuff into the snapshot array:

字符串数组随时间变化,我使用字符串数组来基本上保存 arrayOfStrings 的历史快照。当我需要访问数据的快照数组时,我的问题就出现了。这是我必须将东西放入快照数组的代码:

arrayOfArraysOfStrings[input_index] = arrayOfStrings; // you can assume input_index is updated correctly, I've already checked that.

This appears to be incorrect since when I try to access and print out the contents of the snapshot array, it only prints out the information from the most recent arrayOfStrings. The idea I was going for with this was to store the address of where arrayOfChars is pointing in an entry of the snapshot array so I can access it later.

这似乎是不正确的,因为当我尝试访问和打印快照数组的内容时,它只打印出最近的 arrayOfStrings 中的信息。我想要的想法是存储 arrayOfChars 指向快照数组条目的地址,以便我以后可以访问它。

Right now, access to an entry in the snapshot array is accomplished like this:

现在,访问快照数组中的条目是这样完成的:

arrayOfArraysOfChars[historicalIndex][indexOfTargetChar]

There are several questions I'm looking to answer:

我想回答几个问题:

  1. Is the method I outlined appropriate for what I'm trying to do or is there a flaw in my overall logic?
  2. What am I doing wrong with my current code and how do I fix it?
  3. Is there a better way to do this, and if so, how does initialization of the arrays, addition to the arrays, and reading from the arrays work?
  1. 我概述的方法是否适合我正在尝试做的事情,或者我的整体逻辑是否存在缺陷?
  2. 我当前的代码有什么问题,我该如何解决?
  3. 有没有更好的方法来做到这一点,如果是这样,数组的初始化、数组的添加和从数组中读取是如何工作的?

--edit 4/18-- Part of the problem is that I'm setting pointers in arrayOfArraysOfStrings to point to the same thing that arrayOfStrings is pointing to. That's bad since arrayOfStrings gets edited. I need some way to duplicate a 2D array... Preferably by simply allocating a new block of memory for arrayOfStrings to point at.

--edit 4/18-- 部分问题是我在 arrayOfArraysOfStrings 中设置指针指向 arrayOfStrings 指向的同一事物。这很糟糕,因为 arrayOfStrings 被编辑了。我需要一些方法来复制一个二维数组......最好通过简单地为 arrayOfStrings 分配一个新的内存块来指向。

回答by luser droog

You have one-too-many pointers in both of your arrays.

您的两个数组中的指针都太多了。

char arrayOfChars[50]; // a single array of characters
char *arrayOfArraysOfChars[10]; // array to hold multiple single arrays of characters

Since the arrayOfChars is being used like a buffer (new data always goes there first), you'll need to save a copy of the string into the arrayOfArrays. The POSIX function strdupshould help here.

由于 arrayOfChars 被用作缓冲区(新数据总是首先到达那里),因此您需要将字符串的副本保存到 arrayOfArrays 中。POSIX 函数strdup在这里应该会有所帮助。

Notice &and *are opposites, so &*and *&do absolutely nothing.

公告&*是对立的,所以&**&什么都不做。

You could also, make the arrayOfArrays literally that.

你也可以,让 arrayOfArrays 从字面上看。

char arrayOfChars[50]; // a single array of characters
char arrayOfArraysOfChars[10][50]; // array to hold multiple single arrays of characters

With this setup, you should use strcpyto copy the data into arrayOfArrays.

使用此设置,您应该使用strcpy将数据复制到 arrayOfArrays 中。



Having read your edit, I think you need to start realsimple. And FWIW the variable names are the wrong kind of Hungarian.

阅读您的编辑后,我认为您需要从真正的简单开始。FWIW 变量名是错误的匈牙利语。

For what I think you're trying to do, I'd start with just a single char array. This will be the main buffer, to hold strings that are being input and examined.

对于我认为您正在尝试做的事情,我将从一个字符数组开始。这将是主缓冲区,用于保存正在输入和检查的字符串。

enum { BUFSZ = 50 };
char buf[BUFSZ + 1];

Then you can use it with fgetsor whatever.

然后你可以使用它fgets或其他任何东西。

fgets(buf, BUFSZ, infile);

To save these up in an array, I'd use strdupfor its automatic trimming. If the strings are going to be mostly 2 characters long, I don't want 48 extra bytes being used for each one. So, an array of char pointers (strings).

为了将这些保存在一个数组中,我会使用strdup它的自动修剪。如果字符串的长度主要为 2 个字符,我不希望每个字符串使用 48 个额外的字节。所以,一个字符指针(字符串)数组。

enum { STRVSZ = 40 };
char *strv[STRVSZ + 1];
int i;
i = 0;
strv[i] = strdup(buf);
strv[i+1] = NULL; // This makes it an "argv-style" NULL-terminated array of strings
++i; // i is now the index of the next element, and a count of elements already added

Each element of strvis a char pointer. But to preserve our sanity, we're trying to abstract awaysome of that distracting detail for a moment, and treat stringsas a separate data type.

的每个元素strv都是一个字符指针。但是为了保持我们的理智,我们暂时尝试抽象掉一些分散注意力的细节,并将字符串视为单独的数据类型。

Now to create lists of these, we do the same thing again. But there's no strdup-type function to make a duplicate of an array of pointers, so we have to separate the allocation and copying.

现在要创建这些列表,我们再次做同样的事情。但是没有strdup-type 函数可以复制指针数组,因此我们必须将分配和复制分开。

enum { STRVVSZ = 20 };
char **strvv[STRVVSZ + 1];
int j;
j = 0;
strvv[j] = calloc(i+1, sizeof *strvv[j]); // assuming i is the count of elements 
memcpy(strvv[j], strv, i * sizeof *strvv[j]);
++j; // j is now the index of the next string-pointer array in the array-of-same,
     // and a count of elements already added.

Now, my names are just as silly as yours, but they're shorter!

现在,我的名字和你的名字一样愚蠢,但它们更短!

回答by Dae314

you should learn what an array means. an array is basically a set of integeror characteror anything. when you are storing a character value in an array, define it as,

您应该了解数组的含义。数组基本上是一组整数字符任何东西。当您在数组中存储字符值时,将其定义为,

char array[] = {"somestringhere"};

now you want to store such arrays in an another array. it is simple:

现在您想将此类数组存储在另一个数组中。很简单:

char* array1[];

the array1 will store values, which are of char*type i.e. the address of character arrays. now you want to store these in other array,

array1 将存储char*类型的值,即字符数组的地址。现在你想将这些存储在其他数组中,

char** array2[];

this is, array of [address of arrays] now, all you have to do is;

这就是,[数组地址] 的数组,你所要做的就是;

array1[0] = array; //same as: array1[0] = *array[0];
array2[0] = *array1[0];

Now you've everything you need. Hope you are clear, to the core. :)

现在您拥有所需的一切。希望你是清楚的,核心。:)

回答by steven tahner

This example was done with turbo c+ 1.01 dos and works in the 3.0 dos version also.

这个例子是用 turbo c+ 1.01 dos 完成的,也适用于 3.0 dos 版本。

char * text[] = {
  "message1",
  "message2",
  "message3"
};

回答by pmg

Note that your examples show arrays of pointers. If you want arrays of arrays (multidimensional arrays) specify all the sizes in the array definition.

请注意,您的示例显示了指针数组。如果您想要数组数组(多维数组),请在数组定义中指定所有大小。

char sentences[500][42]; /* sentences is an array of 500 elements.
                         ** each element is itself an array
                         ** capable of holding strings up to length 41 */

回答by steven tahner

if storing text in a .c or .h file having more than one line of text, equivalent to the idea of an array of char arrays. can do this:

如果将文本存储在包含多行文本的 .c 或 .h 文件中,则相当于 char 数组的数组的想法。可以这样做:

char * text[] = {
  "message1",
  "message2",
  "message3"
};

can also use char *text[], char near *text[], char far *text[], char huge *text[]. has to have an asterisk or star character for a pointer.

也可以使用char *text[]、char near *text[]、char far *text[]、char巨大的*text[]。指针必须有星号或星号。

a for loop can be used to display text:

for 循环可用于显示文本:

char i; // int type can also be used
for (i = 0, i < 3; i++)
  printf("%s\n", text[i]);

other loops:

其他循环:

char i = 0;  // may not be zero when declared as "char i;" only
while (i < 3) {
  printf("%s\n", text[i]);
  i++;
 }

or

或者

char i = 0;  // may not be zero when declared as "char i;" only
do {
 printf("%s\n", text[i]);
 i++;
} while (i < 3);