简体   繁体   中英

Copying char array and sort

Aim: to save the latest 5 dates from a very large bank of dates without storing all dates. This will be run on an Arduino style microcontroller, but thought it is more relevant to the C language in general.

My current method is to copy the 6 digit char array of the date (yymmdd) into the last position of a 6 date array, sort from latest to earliest, then iterate over the whole bank of dates.

Here is the complete working code:

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;
}

The code can also be run/edit here: cpp.sh/3rl7y3

The question is: how to take the dependency on pointers and malloc out? ie initialise latestDates[6][7] instead of *latestDates[] .

Here's some code that keeps the array of pointers

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

latestDates[5] = malloc(strlen(newDate) + 1);
strcpy(latestDates[5], newDate);

I'm not claiming it's good code or anything, but it's legal.

Try this (if there is no need to be a pointer)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM