c语言 - 如何将元素添加到索引号为 "array[number of items in array + 1]" 的数组中



我正在尝试编写一个程序,允许用户向数组中添加元素:

#include <stdio.h>
#include <cs50.h>
int main(void)
{
string words[] = {"apple", "bear", "cards"};

string s = get_string("New word:");

s = words[(sizeof(words) / sizeof(words[0])) + 1];

for(int i = 0; i < sizeof(words) / sizeof(words[0]); i++)
{
printf("%sn", words[i]);
}
}

我本来打算将该元素作为索引号words[number of items in words + 1]添加到数组中,但我收到了错误消息error: array index 4 is past the end of the array (which contains 3 elements) [-Werror,-Warray-bounds]

过度分配words数组:

#define MAX_WORDS 10
static int LoadPredefinedWords(string words, string preDefined) {...}
const string predefinedWords = {"apple", "bear", "cards", NULL};
string words[MAX_WORDS] = {NULL};
int NumberOfWords = LoadPredefinedWords(words, predefinedWords);
for(int i = NumberOfWords; i < MAX_WORDS; i++) ...

或者学习使用malloccallocrealloc,您可以在编译器中或在线找到相关文档。

你可以走捷径:

#define MAX_WORDS 10
string words[MAX_WORDS] = {"apple", "bear", "cards", NULL};;
int NumberOfWords = 3;
for(int i = NumberOfWords; i < MAX_WORDS; i++) ...

但在某些时候,您需要了解在以NULL结尾的指针数组上进行迭代。我们倾向于用零值来标记C中事物的结束。字符串只是一个char *,其中字符序列的末尾用标记,也就是;null,并且不要与经常被定义为类似#define NULL void*NULL混淆。

因此,有一个更好的版本,不太可能因为算术错误而出现错误:

pArrayEnd = words + NumberOfWords;
for (string *pIterator = words; pIterator < pArrayEnd; pIterator++) ...

将此页面设为书签以备将来参考。从上到下读一次(可能分几次),然后每天花20分钟研究它。不要被困在试图理解每一个细微之处上,只要在你去写玩具程序的时候吸收它。

将这些也加入书签:

  • http://code-reference.com/c
  • http://c-faq.com/
  • https://pubs.opengroup.org/onlinepubs/000095399/idx/headers.html

据我所知,您需要为这样的任务创建一个动态数组。

您的数组现在具有稳定、恒定的大小,并且不能更改。因此,在最终结构中添加+1元素并不是那么简单。

或者在另一种情况下,您可以创建一个更大的数组,并创建一个变量来存储数组中当前元素的数量。但对于需要进行随机量的"+1〃;操作。

最新更新