0

ユーザーに名前と姓を入力させた後、名前を逆の順序で印刷するようにプログラムする必要があることを除いて、すべて正常に機能する複数のことを実行するプログラムが必要です(John Doe = Doe John)。皆さんからの支援のおかげで、私は適切な機能を持っていると思いますが、まだセグメンテーション違反が発生しています。ここで何が問題なのですか。

プログラムの最後の関数です

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

int main ()
{
    printf("Enter your first and last name\n");

    char name [25]={'\0'};
    char * space;

    fgets(name,sizeof(name),stdin);

    printf("You Entered: %s     \n", name);

    printf("There are %u characters in your name including the space. \n", strlen(name));

    char end;
    int i;
    end = strlen(name) -1;
    printf("Your name backwards is");
    for (i = end; i >= 0; --i)
    {
        printf("%c", name [i]);
    }

    printf("\nLooking for the space in your name \n", name);
    space=strchr(name, ' ');
    while (space!=NULL)
    {
        printf("The space was found at character %d\n", space-name+1);
        space=strchr(space+1, ' ');
    }
    //Why am I getting a segmentation fault (cord dumped) error here?
    *space = '\0';
    printf(" %s %s ", space+1, name);

}
4

2 に答える 2

3

while ループ ブレークspaceが NULL の場合、NULL アドレスに書き込みます。

while (space!=NULL) <-- "loop breaks when space is NULL"
{
    printf("The space was found at character %d\n", space-name+1);
    space=strchr(space+1, ' ');
}
//Why am I getting a segmentation fault (cord dumped) error here? 
*space = '\0';  <--- "space is NULL"

編集:

入力した単語を逆順に出力するには、次のコードを試してください (コメントを読んで理解してください)。

// suppose name is "Grijesh    Chauhan"
char *last = NULL, *firstspcae = NULL; 
firstspcae = space = strchr(name, ' ');
*firstspcae = '\0';  // At first space insert nul char '\0'
while (space != NULL)
{
    printf("The space was found at character %d\n", space-name+1);
    last = space + 1;  //next to space 
    space=strchr(space + 1, ' ');
}
printf("\n%s %s ", last, name);   // "Chauhan Grijesh"
*firstspcae = ' ';  // recover your original  string back 
printf("\n%s %s ", last, name);  // "Grijesh    Chauhan"
于 2013-09-27T15:55:16.033 に答える
1

segfault を取得している行を見つけるより一般的な方法は、フラグをgcc使用してプログラムをコンパイルし (eg )、実行し(eg )、入力すると、segfault の行 (またはエラーのエラー) が表示されます。 sort) とその背後にある理由-ggcc -g file.cgdb'gdb a.outrunwhere

于 2013-09-27T16:30:51.023 に答える