this is my code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char db_names[3][36] = {};
strncpy(db_names[0], "6e64e40c-57f6-11ec-91ca-001a6496977d", 36);
strncpy(db_names[1], "90e852c8-502d-11ec-91ca-001a6496977d", 36);
strncpy(db_names[2], "28712b0e-57f6-11ec-91ca-001a6496977d", 36);
printf("index 0 %s\n", db_names[0]);
printf("index 0 %s\n", db_names[1]);
printf("index 0 %s\n", db_names[2]);
return EXIT_SUCCESS;
}
print element in array :
index 0 : 6e64e40c-57f6-11ec-91ca-001a6496977d90e852c8-502d-11ec-91ca-001a6496977d28712b0e-57f6-11ec-91ca-001a6496977d
index 1 : 90e852c8-502d-11ec-91ca-001a6496977d28712b0e-57f6-11ec-91ca-001a6496977d
index 2 : 28712b0e-57f6-11ec-91ca-001a6496977d
>Solution :
-
Fix the index in the format string.
-
If you want to print a (non-
\0terminated) character array then you have to use a length modifier%.36sto tellprintf()how large the array is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char db_names[3][36]={};
strncpy(db_names[0],"6e64e40c-57f6-11ec-91ca-001a6496977d", 36);
strncpy(db_names[1], "90e852c8-502d-11ec-91ca-001a6496977d", 36);
strncpy(db_names[2], "28712b0e-57f6-11ec-91ca-001a6496977d", 36);
printf("index 0 %.36s\n", db_names[0]);
printf("index 1 %.36s\n", db_names[1]);
printf("index 2 %.36s\n", db_names[2]);
return EXIT_SUCCESS;
}
- Alternatively increase the array to 37 elements and copy the terminating
\0so you are operating on strings:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char db_names[3][37]={};
strncpy(db_names[0],"6e64e40c-57f6-11ec-91ca-001a6496977d", 37);
strncpy(db_names[1], "90e852c8-502d-11ec-91ca-001a6496977d", 37);
strncpy(db_names[2], "28712b0e-57f6-11ec-91ca-001a6496977d", 37);
printf("index 0 %s\n", db_names[0]);
printf("index 1 %s\n", db_names[1]);
printf("index 2 %s\n", db_names[2]);
return EXIT_SUCCESS;
}
-
(Not fixed) Consider a symbolic constants for the length, and/or
sizeofinstead of hard-coding36or37. -
I would initialize the string instead and use a loop to print the result. Used
sizeofof the first string; alternatively leave 37 hard-coded or introduce a symbolic constant#define UUID_LEN 36and useUUID_LEN + 1when declaring the array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char db_names[][sizeof "6e64e40c-57f6-11ec-91ca-001a6496977d"]={
"6e64e40c-57f6-11ec-91ca-001a6496977d",
"90e852c8-502d-11ec-91ca-001a6496977d",
"28712b0e-57f6-11ec-91ca-001a6496977d",
};
for(size_t i = 0; i < sizeof db_names / sizeof *db_names; i++)
printf("index %zu %s\n", i, db_names[i]);
return EXIT_SUCCESS;
}
Either of the 3 programs will output:
index 0 6e64e40c-57f6-11ec-91ca-001a6496977d
index 1 90e852c8-502d-11ec-91ca-001a6496977d
index 2 28712b0e-57f6-11ec-91ca-001a6496977d