I cannot figure out how to assign an integer value to an array of string in C, assuming this is possible of course! I would like to change some elements from a char ** into different values and then re-assign them to their initial position into the array. Practically, I have two element, "Mon" and "Aug", which I would like to become "01" and "08"... So I tried something but unsuccessfully:
char *time_array[7] = {"45", "55", "11", "Mon", "29", "Aug", "2022"};
uint32_t day2convert = 1;
uint32_t month2convert = 8;
*time_array[3] = &day2convert; // not even with a cast (char) which gave same results
*time_array[5] = &month2convert;
for (j = 0; j < 7; j)
printf("after conversion : %s\n", time_array[j]);
/*
Results for the two elements are different at each main call, as I'm randomly picking values present in different memory allocations (maybe). Es. don, hug; 4on 8ug, ton xug... Moreover i tried also with strcpy function as:
strcpy(time_array[3], &day2convert); //also with a cast (char)(&day2convert)
but still I retrieve a void string.
So, gently, I'm asking if there could be a way to do what I want in principle, but also asking for some explanations about array of string. Because what I learnt is that a char ** is an array of pointer so it should be right to assign a value to it as *array[ii] = &var (??? in search of confirmation)
CodePudding user response:
Thanks to Some programmer dude!
I will post the solution just in casa anyone else will encounter the problem in future:
uint32_t a[2];
snprintf(a, 2, "%d\n", day2convert);
time_array[3] = &a;
CodePudding user response:
You will want to convert each of the 7 day names to a number.
I wrote this "hash function" for quickly getting back 1 to 7 for "Sun" to "Saturday" (it only needs the first two characters of the name, and is case insensitive).
It will return false positives, but allows you to test the string you have against only one possible day name. If the function returns 2, then the string can be checked as a variation of "Tu", "TUE" "Tuesday". You don't have to examine the other six day names as possibilities.
Return of 0 indicates it is not a weekday name.
// Convert a day name (or 3 letter abbrev.) to index (1-7, Sun=1). Beware false positives!
int wkdayOrd( char cp[] ) { return "65013427"[*cp/2 ~cp[1] & 0x7] & 0x7; }
If you carefully replace 2 with 1, 3 with 2, 4 with 3, etc. in the quoted string, it will return Mon=1 and Sun=7 as you desire...
And for month names "Jan-December" (3 letters necessary) into 1 to 12. Again, this is a "hash function" and other words can/will result in "false positives" that must be confirmed against only one proper month name string.
int monthOrd( char cp[] ) { return "DIE@CB@LJF@HAG@K"[ cp[1]/4&7 ^ cp[2]*2 &0xF ] &0xF; }
Give it a play and let us know if it helps you get where you want to be.