0

我正在尝试更改数组中的值。但我无法弄清楚如何在没有得到奇怪输出的情况下做到这一点。

char *wordsArray[9] = {"word1","word2","word3","word4","word5","word6","word7","word8","word9"};

int *temp;
temp = &wordsArray[randNumber1];

wordsArray[randNumber1] = wordsArray[randNumber2]; //this works
wordsArray[randNumber2] = temp;                    //this does not

我不熟悉指针,所以此时我不知道我做错了什么欢迎所有帮助。谢谢!

4

3 回答 3

0

Line 4 has the biggest problem. There should be a compiler warning being issued there. Normally something like incompatible pointer.

char *wordsArray[9] = {"word1","word2","word3","word4","word5","word6","word7","word8","word9"};

char *temp; // your array contains char pointers, not integers
temp = wordsArray[randNumber1]; // no need to take the address, you get the array element

wordsArray[randNumber1] = wordsArray[randNumber2];
wordsArray[randNumber2] = temp;                    // now this will work

As a learning exercise: try to forget about pointers:

typedef char * my_string_type;

my_string_type wordsArray[9] = {"word1","word2","word3","word4","word5","word6","word7","word8","word9"};

my_string_type temp = wordsArray[randNumber1];
wordsArray[randNumber1] = wordsArray[randNumber2];
wordsArray[randNumber2] = temp;
于 2013-09-09T15:28:43.277 回答
0

int *temp; should be char* temp

You are trying to store int in char Array.

于 2013-09-09T15:29:39.147 回答
0

诠释*温度;

表示 temp 是一个 int*。此外 int* temp; 与 int *temp 相同;您可以认为 temp 是一个 int* 即指向 int 的指针,而 *temp 是一个 int。

如果你想重现

wordsArray[randNumber1] = wordsArray[randNumber2]; 

使用 temp 的行为:

temp = &wordsArray[randNumber3];

请记住,wordsArray[randNumber3] 是一个 int,而 &wordsArray[randNumber3] 是一个指向 int 的指针。*temp 是一个整数。因此你必须输入

wordsArray[randNumber2] = *temp; 

将 * 和 & 视为另一个的倒数,你正在做这样的事情:

wordsArray[randNumber1] = *&wordsArray[randNumber3]; 

足够有说服力吗?

于 2013-09-09T15:44:08.547 回答