How can I fix this code (c language) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I fix this code (c language)

I need it to go like 1a 2b 3c ... But instead it goes 1aa 2ab ... How can I fix it https://code.sololearn.com/cuDVS7UDOCNq/?ref=app

1st Nov 2023, 6:30 PM
Lalala
Lalala - avatar
4 Answers
+ 5
sprintf(str, "%ld", tid+1); // remove a.... ?
2nd Nov 2023, 4:18 AM
Jayakrishna 🇮🇳
+ 2
also, why are you using long? This gives you errors because you are allocating insufficient capacity in your char[] . if you must use long, then you should also change these to get rid of the errors: char str[21]; char new_element[22]; Or just recast long to int or unsigned int instead since your threads only goes to 26. also, use char new_element[5]; changed from [4] to [5] to account for null terminator error message. https://code.sololearn.com/c7pov45jvq57/?ref=app
2nd Nov 2023, 5:36 AM
Bob_Li
Bob_Li - avatar
+ 1
here is the solution:- void *add_element(void *thread_id) { unsigned int tid = (long) thread_id; char c = 'a' + tid; char str[4]; sprintf(str, "%u", tid+1); char new_element[5]; sprintf(new_element, "%s%c", str, c); printf("%s\n", new_element); pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; int rc; long t; for (t = 0; t < NUM_THREADS; t++) { rc = pthread_create(&threads[t], NULL, add_element, (void *) t); if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } pthread_exit(NULL); }
2nd Nov 2023, 2:17 PM
Alhaaz
Alhaaz - avatar
0
Pito
2nd Nov 2023, 10:00 PM
Gustavo jhair Vera Valencia
Gustavo jhair Vera Valencia - avatar