char newDict[numberWords][28];
dictionary = newDict;
首先这部分是错误的,newDict 是一个数组,它分配在一段内存中,而字典是一个指向指针的指针,它分散在堆的不同部分,因为字典正在寻找一个指针,所以你访问不正确指向一个指针,而 newdict 不包含指针,读取数组和指针,它们是不同的,尽管它们似乎以相似的方式工作
我看到您想使用数组表示法,因此您分配 dictionaty = newdict(这是错误的)
最简单的方法是
char ** dictionary;
dictionary = (char **)malloc(sizeof(char *)*NUMBER_OF_WORDS)
for(int i =0;i<NUM_WORDS,i++)
{
dictionary[i] = (char *)malloc(sizeof(char)*28);
}
now you can access each word like this
dictionary[word_number][the letter];
//so in your code you said char ** dictionaty, lets go through this, dictionary is a
pointer to another pointer that points to a char. look at my code, dictionary is a
pointer, that points to another pointer that eventuall points to a char.
为什么会这样?
数组符号的工作方式如下 a[x] = *(a+x) ,换句话说,转到数组 a,添加 x 并获取该内存位置中的数字,方括号称为语法糖,只是为了使我们的生活更轻松,真正发生的是 *(a+x)。
对于 2d 数组 a[x][y] = * ( *(a+x) + y) 这就是说转到指针 a,将 x 添加到指针中,获取该内存中的任何内容 *(a +x) 然后将 y 添加到该内存中并获取指向 * (* (a+x) + y) 的任何内容
请注意,当我说将 x 添加到指针时,它取决于数组包含的内容,比如你是否有一个 int 数组,因为 int 是 4 个字节,假设 x 是 1,
int a[10]
a[1] = *(a+1) (the compiler actually adds 4 bytes to the address although we
said 1 obviously since an int is 4 bytes, this
is pointer arithmetic you should read up on it. this makes things much easier.
在内存中真正发生的是添加了 4 个字节以到达 a+1 的地址,编译器为我们处理了这个,所以这让事情变得更容易,在你的情况下它是一个字符,所以说 a [1] = *(a+1),
回到你的问题。
dictionary[0][0] 将为您提供第一个单词中的第一个字母,以获取整个字符串,例如 printf 和 %s,因为您的字符串以空值结尾。