+ 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
4 Respostas
+ 5
sprintf(str, "%ld", tid+1); // remove a.... ?
+ 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
+ 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);
}
0
Pito