【发布时间】:2015-06-30 23:13:03
【问题描述】:
我是 C 的新手,我主要将 C 程序迁移/重新实现到 Java 等。我正在尝试学习 C,我已经阅读了几个教程。我有一个程序尝试通过char *argv 从命令行读取用户输入(数字),对这些数字进行排序,然后将排序后的数字打印出来。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
//if the is argument supplied
if (argc > 1)
{
int count = 0;
//array to sort less 1
count = argc -1;
int tobe_sorted[count];
int i=0;
//allocate memory for target result array
int *target = malloc(count * sizeof(int));
//copy unsorted ints to target
memcpy(target, tobe_sorted, count * sizeof(int));
//sort target using bubble sort
int temp =0;
int x =0;
int y=0;
for (x=0; x<count; x++ )
{
for (y=0; y<count -1; y++ )
{
if (target[i]>target[i+1])
{
temp = target[i+1];
target[i+1] = target[i];
target[i] = temp;
}
}//end inner
}//end outer
//end bubble sort
x=0;
printf("Sorted:\n");
//print sorted array
while (x <count)
{
printf("%d",target[x]);
printf(",");
x++;
}
printf("\n");
}//end argument supplied
else{
printf("Error, please enter numbers to be sorted\n");
}
return 0;
}//end main function
我的意见
PS C:\Users\xyz\workspace_cpp\the_hard_way\ex18> .\sort_test.exe 5 4 3 2 1
输出
Sorted:
2686748 1986196690 32 1 4199492
- 我不确定 C 打印的是什么,这些是 ASCII 码吗?
- 为了打印已排序的 int 数组,我需要在上述程序中修复什么?
免责声明:我不希望使用诸如 qsort() 之类的库函数,也不想让程序更高效。
基于 cmets 编辑和工作的代码(在目标数组中分配了一个额外的索引,否则排序和 char 到 int 的转换工作):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
//if thee is argument supplied
if (argc > 1)
{
int count = 0;
count = argc;
int tobe_sorted[count-1];
//initialize with 0's
int i=0;
for (;i<count; i++)
{
tobe_sorted[i] = 0;
}
//populate tobe_sorted with integer values of argv
i=0;
for (;i<count; i++)
{
tobe_sorted[i] = atoi(argv[i]);
}
//allocate memory for target result array
int *target = malloc((count * sizeof(int)));
//copy unsorted ints to target
memcpy(target, tobe_sorted, count * sizeof(int));
//sort target using bubble sort
int tmp =0;
int x =0;
int y=0;
int swapped = 1;
while (swapped)
{
swapped =0;
y++;
for (x=0; x < count - y; x++)
{
if (target[x] > target[x+1])
{
tmp = target[x];
target[x] = target[x+1];
target[x+1] = tmp;
swapped = 1;
}
}
}
//end bubble sort
x=0;
printf("Sorted:\n");
//print sorted array
while (x <count)
{
printf("%d",target[x]);
printf(",");
x++;
}
printf("\n");
}//end argument supplied
else{
printf("Error, please enter numbers to be sorted\n");
}
return 0;
}//end main function
输入:
PS C:\Users\xyz\workspace_cpp\the_hard_way\ex18> .\sort_test.exe 5 -3 -2 1 8
输出 排序: -3,-2,0,1,5,8,
【问题讨论】:
-
首先要确定你是想学习 C 还是 C++,并正确设置标签。
-
memcpy(target, tobe_sorted, count * sizeof(int));看起来不对。tobe_sorted未初始化。您的意思是使用argv吗?即使是这样,那仍然是错误的。argv值是字符串而不是整数。您需要将每个 argv 字符串转换为带有atoi或strtol的 int。
标签: c