2017-08-30 7 views
0

現在、プロジェクト中に発生した問題を解決しようとしています。私は行列にファイル(マップ)の内容を読み取ることがありますが、最初の行は、4つの別々の文字が含まれていますreadテキストを使用してテキストをファイルを行列の中に作成する

  1. 空の文字の
  2. 代表障害物キャラクタの代表の数を
  3. 全英文字の代表者です。これらは私が配列で入力する必要があります。

コード:

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <stdlib.h> 
#include "head.h" 

#define BUF_S 4096 

char **ft_build_martrix(char *str, int *pr, int *pc, char *blocks) 
{ 
    int  fd; 
    int  ret; 
    int  ret2; 
    int  j; 
    char *res[BUF_S + 1]; 

    j = 0; 
    fd = open(str, O_RDONLY); 
    if (fd == -1) 
    { 
     ft_putstr("map error"); 
    } 
    ret2 = read(fd, blocks, 4); //take the first row out and put it into the array 
    ret = read(fd, res, BUFF_S); //read the file's content into the matrix 
    res[ret][0] = '\0'; 
    *pr = blocks[0] - '0'; // give the number of rows to the r variable that is declared in main and passed as argument, I think that's the equivalent of the $r in c++ ? 
    blocks[0] = blocks[1]; // delete the 
    blocks[1] = blocks[2]; // first character 
    blocks[2] = blocks[3]; // that is already in *pr 
    while (res[1][j] != '\n') 
     j++; 
    *pc = j; // get the number of column 
    return (res); 
} 
+5

実際の質問は何ですか? – Art

+0

エラー(BUF_S vs BUFF_S)のためコードがコンパイルされず、resの割り当てがないため、問題が何かを知るのが少し難しい –

+0

gccコンパイラは読み取り構文を受け入れません。関数の宣言はC99では無効であると言われています。 – Samuel

答えて

0

あなたはローカル変数へのポインタを返すされています。関数から戻ると、ローカル変数はスコープから削除され(その存続期間は終了しています)、このアドレスにアクセスすると(これ以上あなたのものではない)未定義の動作が発生します。あなたは未定義の動作を呼び出しているret != 0でこの動作を

res[ret][0] = '\0'; 

を適用した場合

はまた、これはへのポインタの配列

char * res[BUF_S + 1]; 

+---+   +---+ 
| * |--------->| | res[0][0] (*ret)[0] 
+---+   +---+ 
res   | | res[0][1] 
       +---+ 
       | | ... 
       +---+ 
       | | res[0][BUF_S + 1 - 1] 
       +---+ 

の宣言です。


あなたは(へのポインタへのポインタ文字

char ** res = malloc(sizeof(char*) * X); // Where X is number of rows 

そして、すべての行を別々

for (int i = 0; i < X; i++) 
{ 
    res[i] = malloc(BUF_S + 1); 
} 

が次にあなたが異なるアクセスすることができ、このようにそれを宣言する必要が'rows'(最大X-1X以上は、境界外のアクセスや未定義の動作につながります)。

次に、メモリを解放します。

関連する問題