简体   繁体   中英

Simple C program involving arrays cannot execute

I have a homework problem which requires me to convert a word a user entered to Pig Latin by moving the first letter of the word to the end and adding an ay to it. For example, Tuesday becomes uesdayTay. This process should be repeated until the user types STOP.

I'm really new to arrays, so I might be using them wrongly, but I can't find out why. The program I wrote can be compiled but crashes whenever I execute it. I'm sure this program is rather simple, but here is my code:

#include <stdio.h>
#include <string.h>

int main ()
{
    char *input_word [100], *temp [100], *stop [4];
    int n = 0;

    printf("Enter a word: ");
    for( n = 0; n < 100; n++)
    { 
        scanf("%s", input_word[n]);
    }


    while (  strcmp ( stop [4], "STOP" ) != 0 )
    {
        *temp = input_word [0];
        for ( int j = 1; j <= n-1; j++)
        {
            *input_word [j-1] = *input_word [j];
        }

        input_word [n-1] = *temp;

        printf("%s", *input_word);
        printf("ay\n");

        printf("Type STOP to terminate: ");
        for ( n = 0; n < 4; n++ )
        {
            scanf("%s", stop[n] );
        }

    }

    return 0;


}

Can anyone please help me out? I find arrays to be rather confusing. Thanks!

scanf("%s", input_word[n])

I will stop you already there.

You declared input_word as an array of pointers, but those pointers are 1. not initialized 2. not pointing to valid memory that you need to allocate.

Instead first declare an array to hold the input from the user

char input_word[100];

Now to keep things simple, use fgets to read from the command line

fgets(input_word, sizeof(input_word), stdin);

Now remove the trailing \\n if any:

 char* p = strchr(input_word, '\n'); 
 if (p) 
 {
   *p = '\0';
 }

Now you have "Tuesday\\0" (if you entered that word) in input_word.

Have another array for the new word:

char output_word[100] = { '\0' };

Skip the first character and copy until end of string:

strcpy(output_word, input_word + 1);

Now take the first character and add it:

strncat(output_word, input_word, 1);

Then add the rest using strcat, and sprinkle code with checks like length of string entered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM