我正在尝试编写一个程序,允许用户向数组中添加元素:
#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++) ...
或者学习使用malloc
、calloc
和realloc
,您可以在编译器中或在线找到相关文档。
你可以走捷径:
#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 *
,其中字符序列的末尾用