gpt4 book ai didi

更改 PointerArray 的值

转载 作者:行者123 更新时间:2023-11-30 17:48:07 25 4
gpt4 key购买 nike

我正在尝试更改数组中的值。但我不知道如何在不得到奇怪输出的情况下做到这一点。

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号线的问题最大。那里应该会发出编译器警告。通常类似于不兼容的指针。

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;

关于更改 PointerArray 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18701721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com