0

セグメンテーション違反が発生します

そのため、上部にtypedef char*stringがあります。

それから私はちょうど約5に設定されているスペースと呼ばれる変数を持っています

for(i=0; i<=spaces; i++) {
    sepwords[i] = malloc(3000);
}

strはchar配列です。スペースを探して、それまでコピーしています。

while(str[i]!=' ') {


    printf("%d\n", i);
    strcpy(sepwords[i], "hello");
    i++;

}

実際に機能するように

しかし、私がそうするなら

while(str[i]!=' ') {
    char *temp[100];
    *temp=str[i];


    printf("%d\n", i);
    strcpy(sepwords[i], *temp);
    i++;




}

これで障害が発生します

事前にメモリを割り当てていたので、typedef文字列を使用しているためではないと思います。

何か案は?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 256

char *progn;

void usage(void) {
    fprintf(stderr, "Usage: %s pattern\n", progn);
}
typedef char * string;

int pattern_match(char *pattern, char *str) {






int i=0;
int spaces=0;

while(str[i]!=0) {
    if(str[i]==' ') {
        spaces++;
    }
    i++;
}
string sepwords[spaces];





for(i=0; i<=spaces; i++) {
    sepwords[i] = malloc(3000);
}


i=0;


while(str[i]!=' ') {
    char *temp[100];
    *temp=str[i];


    printf("%d\n", i);
    strcpy(sepwords[i], temp);
    i++;




}









//printf("%d\n", spaces);



//strs[0]="hiya boy";
//printf(strs[1]);





}

int main(int argc, char **argv) {

    char line[MAXLINE];
    char *pattern;
    progn = argv[0];

    if (argc != 2) {
        usage();
        return EXIT_FAILURE;
    }
    pattern = argv[1];

    while (!feof(stdin) && !ferror(stdin)) {
        if (!fgets(line, sizeof (line), stdin)) {
            break;
        }
        if (pattern_match(pattern, line)) {
            printf("%s", line);
        }
    }
    if (ferror(stdin)) {
        perror(progn);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
4

2 に答える 2

1

コードに2つの構文エラーがあります。あなたのコンパイラはそれらについてあなたに警告したに違いありません:

* temp = str [i];

tempはchar*[100]、* tempはchar*であるtemp[0]と同等です。しかし、str[i]はcharです。つまり、char(シングルバイト)をchar *(アドレス)に入れているということです。

strcpy(sepwords [i]、temp);

tempは100文字*の完全な配列のアドレスであるため、ゼロバイトが見つかるまで大きな文字列のようにコピーします。

このエラーもあります:

文字列sepwords[スペース];

for(i = 0;i<=スペース;i++){

sepwords[i] = malloc(3000);

文字列sepwords[spaces]は0からspaces-1までの「スペース」長の配列を割り当てるため、i<=スペースではなくi<スペースです。

最後:入力にスペースが含まれていない場合、while(str [i]!='')に終了条件はありません。これは、終了の世話をすることになるため、セグメンテーション違反が発生する場所です(gdbは友達です)。 strの(最後の\ 0バイトを過ぎて)

于 2013-02-27T23:00:47.800 に答える
0
  1. char *を文字列として定義する代わりに、pcharとして定義します。char *は文字列ではなく、文字へのポインタです。文字のアドレスである場合とそうでない場合があり、メモリ内で0で終わる他の文字が続く場合があります。undefined_pchar=セグメンテーション違反の値であるため、これは重要です。undefined_string=""の値。

  2. fprintf(stderr, "Usage: %s pattern\n", progn);これは未定義のprognを出力します。不正なメモリ、またはメモリのランダムなコレクションである可能性があります。どちらの場合も悪い。pchar progn = 0したがって、この概念を理解していることを示すために、prognを宣言するときに示す必要があります。

  3. sepwordsはchar*であり、sepwords [i]はcharです。つまり、sepwords [i] = malloc(3000)は、コンパイルされたとしても、表記の誤用になります。cスタイルの文字列のリストを作成するには、代わりにpchar*を使用してください。

    for(i = 0; i <= space; i ++){sepwords [i] = malloc(3000); }

エラーを見つけてみたいと思いますが、コメントまたは適切なタイプの使用法のいずれかによって、あなたが何をしようとしているのかを理解するために、意図がある程度明確である必要があります。

于 2013-02-27T22:32:21.987 に答える