在C中打印排序数组时获得奇怪的输出
我正在开发一个程序,该程序从命令行获取任意数量的参数,将它们切成两半,放入数组,按字母顺序排序,然后按顺序打印。它最多可以使用三个参数,但之后会给出一些奇怪的输出。以下是我到目前为止的情况:在C中打印排序数组时获得奇怪的输出,c,C,我正在开发一个程序,该程序从命令行获取任意数量的参数,将它们切成两半,放入数组,按字母顺序排序,然后按顺序打印。它最多可以使用三个参数,但之后会给出一些奇怪的输出。以下是我到目前为止的情况: #include <stdio.h> #include <string.h> #include <stdlib.h> struct string { char *first_half; char *second_half; }; int cstring
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct string {
char *first_half;
char *second_half;
};
int cstring_cmp(const void *a, const void *b);
int arrayIndex = 0;
int main(int argc, char *argv[])
{
int numArguments = argc;
char **new_array = malloc(argc * sizeof(char*));
struct string word;
for (int i = 1; i < argc; i++)
{
int len = strlen(argv[i]);
int len_first = len/2;
int len_second = len - len_first;
word.first_half = malloc( (len_first + 1) * sizeof(char) );
word.second_half = malloc( (len_second + 1) * sizeof(char) );
memcpy(word.first_half, argv[i], len_first);
memcpy(word.second_half, argv[i]+len_first, len_second);
new_array[arrayIndex] = word.first_half;
if(word.second_half != " ")
new_array[arrayIndex+1] = word.second_half;
arrayIndex += 2;
//free(word.first_half);
//free(word.second_half);
}
qsort(new_array, ((argc - 1)*2), sizeof(char *), cstring_cmp);
for (int i = 0; i < ((argc - 1)*2); ++i)
{
printf("%s\n", new_array[i]);
}
return 0;
}
int cstring_cmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}
#包括
#包括
#包括
结构字符串{
字符*前半部分;
字符*第二个半字符;
};
int cstring_cmp(常数无效*a,常数无效*b);
int-arrayIndex=0;
int main(int argc,char*argv[])
{
int numArguments=argc;
char**new_数组=malloc(argc*sizeof(char*));
结构字符串字;
对于(int i=1;i
您没有将单词的前半部分和单词的后半部分设置为'\0'
。因此,比较函数在调用strcmp
中会有未定义的行为,因此printf
也会有未定义的行为,因为它们都期望指向以null结尾的字符串的指针
此外,您没有为新的\u阵列
分配足够的资源。它必须包含两个argc-1
元素
if(word.second\u half!=”)
如果不触发也会导致问题,因为您将在new\u数组中保留未初始化的位置,因此上述函数将获得无效指针。请在帖子中包含这些奇怪的输出。刚刚添加了它,谢谢。