gpt4 book ai didi

c - 由于排序功能导致的段错误

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

调用函数 sort_array 在运行时给我错误 segmentation fault (core dumped)

#include <stdio.h>
#define SIZE (40)

void sort_array(unsigned char *arr[],int n)
{
unsigned char tmp;
for (int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[j]>arr[i])
{
tmp=*arr[i];
*arr[i]=*arr[j];
*arr[j]=tmp;
}
}
}
}
int main() {

unsigned char test[SIZE] = { 34, 201, 190, 154, 8, 194, 2, 6,
114, 88, 45, 76, 123, 87, 25, 23,
200, 122, 150, 90, 92, 87, 177, 244,
201, 6, 12, 60, 8, 2, 5, 67,
7, 87, 250, 230, 99, 3, 100, 90};
sort_array(test,SIZE);

for(int i=0;i<SIZE;i++)
printf("%c ,",test[i]);

}

最佳答案

问题在于您的函数数据类型,您不需要将其定义为 unsigned char *arr[]

修改后的版本:

void sort_array(unsigned char *arr,int n)
{
unsigned char tmp;
for (int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[j]>arr[i])
{
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
}
}
}

关于c - 由于排序功能导致的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57337533/

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