gpt4 book ai didi

c - 交换字符串数组中的元素

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:05 25 4
gpt4 key购买 nike

我正在尝试创建一个程序来生成随机测试用例。我有一个有序的字符串数组 (char **),我想将它们随机化。我的方法是随机选择两个元素并交换它们。但是,我不断遇到段错误,似乎遗漏了一些知识。

示例数组(64 个元素):{"1 2 3", "3 2 1", "4 5 6".....}

char ** randomizeOrder(char ** list, int size){

char temp[6];
temp[5] = '\0';

srand(time(NULL));
int count = 64;
int x, y;
while(count > 0){
fprintf(stderr, "Starting...\n");
x = rand() % 64;
y = rand() % 64;

strcpy(temp, list[x]);
fprintf(stderr, "Copying %s from Y to X\n", list[y]);
strcpy(list[x], list[y]);
fprintf(stderr, "Copying %s from temp to Y\n", temp);
strcpy(list[y], temp);
count--;
}

return list;

}

它似乎适用于前几个元素,然后开始读取垃圾。元素和数组一样被分配,所有元素都打印得很好。有什么想法出了什么问题吗?

最佳答案

认为您应该只交换指针,而不是字符串内容本身。 char** 当然只是一个指针数组。

看起来像这样:

while(count > 0){
x = rand() % 64;
y = rand() % 64;

char* tmp = list[x];
list[x] = list[y];
list[y] = tmp;
count--;
}

如果你想变得非常聪明,你可以使用this trick :

while(count > 0){
x = rand() % 64;
y = rand() % 64;

list[x] |= list[y];
list[y] |= list[x];
list[x] |= list[y];

count--;
}

关于c - 交换字符串数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42215963/

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