下面是该程序的工作副本:
#include <cstdio>
#include <cstdlib>
#include <cstring>
char** bubble_sort(const char **filenames, int n)
{
int i;
char **new_list;
new_list = (char**) malloc(sizeof(*new_list) * n);
for (i = 0; i < n; i++)
{
new_list[i] = (char*) filenames[i];
}
printf("Initial list:\n");
for (i = 0; i < n; i++)
{
printf("%d: %s\n", i, new_list[i]);
}
int x;
int y;
printf("List is sorted:\n");
for(x=0; x<n; x++)
{
for(y=0; y<n-1; y++)
{
if(strcmp(new_list[y],new_list[y+1])>0)
{
char *temp = new_list[y+1];
new_list[y+1] = new_list[y];
new_list[y] = temp;
}
}
}
for (i = 0; i < n; i++)
{
printf("%d: %s\n", i, new_list[i]);
}
return new_list;
}
int main(){
const char *ar[5]={
"eee", "aaa", "bbb", "ccc", "ddd",
};
bubble_sort(ar, 5);
return (0);
}
但是,请记住,您的编程风格更类似于到C比C++(这并不总是一件坏事)。
如果您想为您的数组元素分配新的字符串,你应该改变首先为这样的:
for (i = 0; i < n; i++)
{
//new_list[i] = (char*) filenames[i];
new_list[i] = (char*) malloc(sizeof(**new_list) * (strlen(filenames[i]) + 1));
strcpy(new_list[i], filenames[i]);
}
这是Ç版本(第一个是C++版本)。需要注意的是字符串数组有其所有元素新分配的,而不是使用初始字符串从输入参数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** bubble_sort(char **filenames, int n)
{
int i;
char **new_list;
new_list = malloc(sizeof(*new_list) * n);
for (i = 0; i < n; i++)
{
//new_list[i] = (char*) filenames[i];
new_list[i] = malloc(sizeof(**new_list) * (strlen(filenames[i]) + 1));
strcpy(new_list[i], filenames[i]);
}
printf("Initial list:\n");
for (i = 0; i < n; i++)
{
printf("%d: %s\n", i, new_list[i]);
}
int x;
int y;
printf("List is sorted:\n");
for(x=0; x<n; x++)
{
for(y=0; y<n-1; y++)
{
if(strcmp(new_list[y],new_list[y+1])>0)
{
char *temp = new_list[y+1];
new_list[y+1] = new_list[y];
new_list[y] = temp;
}
}
}
for (i = 0; i < n; i++)
{
printf("%d: %s\n", i, new_list[i]);
}
return new_list;
}
int main(){
char *ar[5]={
"eee", "aaa", "bbb", "ccc", "ddd",
};
bubble_sort(ar, 5);
return (0);
}
我唯一的建议是,你使用std :: vector的。在不使用单个断言检查的情况下围绕char **的并使用sizeof来玩是太频繁的组合,这几乎总是导致令人讨厌的错误。而且,“malloc”?根据我的经验,这在C++中几乎是不需要的。如果你确实需要分配原始数组而不是使用std :: vector,那么使用new []和delete [] - 这是你应该做的。 – 2010-07-06 14:51:58
如果我必须返回char **,该怎么办? (在这种情况下,我确实......我正在使用SDK并且需要char **) – Brandon 2010-07-06 14:53:37
使用STL容器进行所有操作,然后将结果复制到正确分配的char数组。例如:“char ** pp = new char [1000] [1000];”,但不能与malloc! – 2010-07-06 14:55:56