c-复制char数组和排序



目标:从一个非常大的日期库中保存最近的5个日期,而不存储所有日期。这将在Arduino风格的微控制器上运行,但通常认为它与C语言更相关。

我目前的方法是将日期(yymmdd(的6位字符数组复制到6个日期数组的最后一个位置,从最新到最早排序,然后迭代整个日期组。

以下是完整的工作代码:

int compareDates(const void *a, const void *b) 
{ 
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return -strcmp(*ia, *ib);
} 
int main(){
char *latestDates[] = {"200418","991201","020718","050607","121030","000000"};
size_t len = sizeof(latestDates) / sizeof(char *);
char newDate[][7] = {"071122","150101"};
size_t numNewDates = sizeof(newDate)/sizeof(newDate[0]);
for(uint i=0; i<numNewDates; i++){
latestDates[5] = (char*)malloc(7);
strcpy( latestDates[5], newDate[i] );
cout << "Before sort: " << i << endl;
for (int i=0; i<6; i++)
{
cout << latestDates[i] << endl;
}
qsort(latestDates, len, sizeof(char *), compareDates);
cout << "After sort: " << i << endl;
for (int i=0; i<6; i++)
{
cout << latestDates[i] << endl;
}
}
free(latestDates[5]);
return 0;
}

代码也可以在这里运行/编辑:cpp.sh/3rl7y3

问题是:如何消除对指针和malloc的依赖?即初始化CCD_ 1而不是CCD_。

以下是一些保持指针数组的代码

char *latestDates[] = {"200418","991201","020718","050607","121030","000000"};
char newDate[] = "551122";
latestDates[5] = malloc(strlen(newDate) + 1);
strcpy(latestDates[5], newDate);

我并没有声称这是一个好的代码或任何东西,但它是合法的。

试试这个(如果不需要指针(

char latestDates[][7] = {"200418","991201","020718","050607","121030","000000"};

最新更新