我正在尝试更改数组中的值。 但我无法弄清楚如何做到这一点而不会产生奇怪的输出。
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
我不是指针,所以此刻我不知道我做错了什么 欢迎所有帮助。谢谢!
答案 0 :(得分:0)
第4行是最大的问题。应该在那里发出编译器警告。通常是类似不兼容的指针。
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
作为一项学习练习:试着忘记指针:
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;
答案 1 :(得分:0)
int *temp;
应为char* temp
您正试图将int
存储在char
数组中。
答案 2 :(得分:0)
int * temp;
表示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是一个int。从而 你必须输入
wordsArray[randNumber2] = *temp;
想想*和&作为另一个的倒数,你正在做这样的事情:
wordsArray[randNumber1] = *&wordsArray[randNumber3];
足够令人信服?