Trying to create a multi threaded C program that prints a string in reverse order

笑着哭i 提交于 2020-03-26 04:02:54

问题


I am working on an assignment for my C coding class that requires us to create multiple threads that run different functions. As to ease my confusion, I am trying to do the program one thread at a time, but I am having some trouble. Here is my code:

   #include <pthread.h>
   #include <stdio.h>
   #include <stdlib.h>
   #include <math.h>
   #include <string.h>

   void * print_string_in_reverse_order(void *str)
   {
       // This function is called when the new thread is created
       printf("%s","In funciton start_routine(). Your string will be printed backwards.");
       char *word[50];
       strcpy (*word, (char *)str);

       int length = strlen(*word);

       for (int x = length-1; x >= 0; x--){
          printf("%c",&word[x] );
       }
       pthread_exit(NULL); // exit the thread
   }

int main(int argc, char *argv[])
{
    /* The main program creates a new thread and then exits. */
    pthread_t threadID;
    int status;
    char input[50];
    printf("Enter a string: ");
    scanf("%s", input);
    printf("In function main(): Creating a new thread\n");
    // create a new thread in the calling process
    // a function name represents the address of the function
    status = pthread_create(&threadID, NULL, print_string_in_reverse_order, (void *)&input);

    // After the new thread finish execution
    printf("In function main(): The new thread ID = %d\n", threadID);

    if (status != 0) {
            printf("Oops. pthread create returned error code %d\n", status);
            exit(-1);
    }
    printf("\n");

    exit(0);
 }

At present, while I have no compiler errors, it does not print anything and does not appear to reverse the string in any way. I am very new to C so I assume it is something like errors with my pointers, but even after several changes and attempts I can't seem to figure out what's wrong. Does anyone have an idea?


回答1:


If word is supposed to be a char array holding a string, the line

char *word[50];

should be changed to:

char word[50];

Also, the line

strcpy (*word, (char *)str);

should be changed to:

strcpy (word, (char *)str);

In additon, the line

printf("%c",&word[x] );

should be changed to:

printf("%c", word[x] );

Also, before returning from function main(), you must wait for the created thread to finish executing, by adding the following line:

pthread_join( threadID, NULL );

Otherwise, your thread may be terminated prematurely.



来源:https://stackoverflow.com/questions/60480270/trying-to-create-a-multi-threaded-c-program-that-prints-a-string-in-reverse-orde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!