1

これは私の最初の質問ですので、役に立たない質問でしたら申し訳ありません。

ユーザーがいくつかのパラメーターを使用してコマンドラインからプログラムを呼び出すシミュレーターのこのプロジェクトがあります。のようにMYPROG [options] filename

ファイル名が有効であることを確認する必要があります (ディレクトリ)。さらに使用するために名前を取得する必要があります。

コードの一部を次に示します。

char* ExtrairNome(char* alvo){
    char* teste = alvo;
    char* nome = NULL;
    int barras = 0;

    while(strcmp(teste, "") != 0){ //look for "/"
        if (teste[0] == '/') barras++;
        teste++;
    }

    teste = alvo;
    if (barras > 0){
        while(barras > 0){ //remove everything leaving the "filename.ias"
            if (teste[0] == '/') barras--;
            teste++;
        }
    }

    int i = 0;
    char aux[strlen(teste) - 4];
    while (strcmp(teste, ".ias")){ //remove the ".ias"
        aux[i] = teste[0];
        teste++;
        i++;
    }
    printf("random %d\n", barras); //this line fixes the bug!!
    aux[i] = '\0';
    nome = aux;
    return nome;
}

この関数は、完全なファイル名を含む文字列を受け取り、拡張子やパスなしで名前のみを返す必要があります。しかし、戻る前にいくつかの変数を印刷した場合にのみ機能します。その行を削除すると、関数は何も返しません。範囲と関係があると思いますが、よくわかりません。どうすればこれを修正できますか?

4

2 に答える 2

1

nome はポインタなので、解のアドレスを返すことができます。問題はスタックにある aux で、戻るともう存在しないため、動作は不明です。より高いスコープで「aux」を宣言して関数に渡すか、ポインタをバッファ ソリューションに渡すか、(malloc を使用して) 関数に割り当ててから解放します (必要でない場合)。

つまり:

char name[100];
ExtrairNome(alvo, name);//pass a pointer to the function

void ExtrairNome(char * alvo, char * aux)
{
     ...;//everything is the same
     //except you don't create aux here, you use the one you created in your main function
}

また

char * ExtrairNome(char * alvo, char * aux)
{
     ...;//everything is the same
     char * aux = (char*)malloc((strlen(teste)-4 )* sizeof(char));
     ...;//everything the same
}
//remember to free() when you are done using it
于 2013-11-07T04:21:40.680 に答える
0

ローカル自動(スタック)変数へのポインターを返しています-aux。関数が戻った後は存在しません。これは未定義の動作です。変数を出力するときに「機能する」という事実は、未定義の動作の可能性です。

于 2013-11-07T04:00:23.290 に答える