セグメンテーションエラーがでます

このQ&Aのポイント
  • Cでオセロゲームを作っています。コンピュータと対戦できるようにしたいのですが、セグメンテーション違反になってしまいます。
  • 局所変数にして関数で受け渡しをすると、数回ループさせたところでエラーで強制終了します。
  • 関数find_legal_moveへのp[]の渡し方が悪いのだと思いますが、なぜか分かりません。
回答を見る
  • ベストアンサー

セグメンテーションエラーがでます

今、cでオセロゲームを作っています。 コンピュータと対戦できるようにしたいのですが、セグメンテーション違反になってしまいます。 p[LEN*LEN]を大域変数にするとうまく動きますが、以下のように局所変数にして関数で受け渡しをすると、 数回ループさせたところでエラーで強制終了します。 おそらく関数find_legal_moveへのp[]の渡し方が悪いのだと思いますが、なぜか分かりません。 以下にプログラムの一部を載せますので、お手数ですが原因を教えていただけないでしょうか。 よろしくお願いします。 #define LEN 10 /* ボードの1辺 */ #define opponent(player) (3-(player)) /* 1の相手は2, 2の相手は1 */ typedef struct {  int row; /* 行 */  int col; /* 列 */  int dr, dc; /* 行, 列の向き */ } Position; // 裏返る石の個数 int count_turn_over(int board[][LEN], int player, Position p) {  int i;  for (i=1; board[p.row+i*p.dr][p.col+i*p.dc]==opponent(player); i++);  if (board[p.row+i*p.dr][p.col+i*p.dc] == player)   return i - 1;  else   return 0; } // playerが(row, col)に石を置けるかどうかをチェック int is_legal_move(int board[][LEN], int player, Position p) {  if ((p.row < 1 || p.row > 8) || (p.col < 1 || p.col > 8))   return 0;  if (board[p.row][p.col] != 0) return 0;  for (p.dr = -1; p.dr <= 1; p.dr++)   for (p.dc = -1; p.dc <= 1; p.dc++)    if (count_turn_over(board, player, p) != 0)     return 1;  return 0; } // playerがどこに石を置けるか int find_legal_move(int board[][LEN], int player, Position p[]) {  Position pos;  int i = 0;  for (pos.row = 1; pos.row < LEN - 1; pos.row++)   for (pos.col = 1; pos.col < LEN - 1; pos.col++)    if (is_legal_move(board, player, pos) != 0) {     p[i].row = pos.row;     p[i].col = pos.col;     i++;    }  return i; } // computerの入力 void computer(int board[][LEN], int player, Position *pos) {  int i, num, max;  Position p[LEN * LEN];  printf("コンピュータの番です\n");  // 一番多く取れるところを取る  num = find_legal_move(board, player, p);  max = count_turn_over(board, player, p[0]);  pos->row = p[0].row;  pos->col = p[0].col;  for (i = 1; i < num; i++) {   int tmp = count_turn_over(board, player, p[i]);   if (max < tmp) {    pos->row = p[i].row;    pos->col = p[i].col;   }  } }

質問者が選んだベストアンサー

  • ベストアンサー
  • Tacosan
  • ベストアンサー率23% (3656/15482)
回答No.5

ん~, ぱっと見た感じだと「computer の中で count_turn_over を直接呼んでいる」のがあやしいんだけどなぁ.... この引数の p[?] で dr とか dc ってメンバがきちんと初期化されていないという可能性を感じたんだけどねぇ. ちなみに computer の中で count_turn_over を直接呼んでいるので, コメントとやってる内容が違うんだけどなぁ.... まあ, もともとデバッガ使っておいかけるのが正しいような気がする.

beginner07
質問者

お礼

回答ありがとうございます。 すいません、さっきチェックが甘かったようで、 max = count_turn_over() の所で、おっしゃるとおりp[0]が初期化されていませんでした。 cygwinでデバッガを使っていないので、printfデバッグでやりました。 max = 0; for (p[0].dr = -1; p[0].dr <= 1; p[0].dr++)  for (p[0].dc = -1; p[0].dc <= 1; p[0].dc++)   max += count_turn_over(board, player, p[0]); としたところ(tmpも同様に)、正常に動くようになりました。 ありがとうございます。

その他の回答 (5)

  • Tacosan
  • ベストアンサー率23% (3656/15482)
回答No.6

老婆心ながら: どうせ最終的に足し算しないといけないんだから, is_legal_move で「count_turn_over の総和」を返す方がいいような気がする. それを記憶するなり, 最大のものを覚えておくなりした方がプログラムとして簡単 (かつ速い) んじゃないかな. あと, find_legal_move の if 文は, is_legal_move の返り値を比較しないで if (is_legal_move(...)) の形にした方がきれいだと思います.

beginner07
質問者

お礼

色々とアドバイスありがとうございます。 まだまだ未熟だと再確認できました。これを参考にプログラミングの勉強をしていきたいと思います。

  • Tacosan
  • ベストアンサー率23% (3656/15482)
回答No.4

#2 です. 盤面の情報は board[][] に入っているでしょうから大丈夫だと思います>#3. で, 本質的には「構造体 Position の作りがおかしい」ということになります. この Position のおかしさがプログラム上のややこしさにつながり, 最終的におかしな挙動につながっていると思います. 具体的にいうと, Position の中に「方向」を表すメンバである dr や dc が入っているのが変. これは count_turn_over の中でまわすためだけに必要なので, Position のメンバとしては不要です. ところで, このプログラムは「コンピュータがパスしなければならないような局面」で不都合がありそうなんだけど... 気のせい?

beginner07
質問者

お礼

何度もありがとうございます。 確かに、引数が増えるのが嫌で構造体にdr,dcを入れたのが悪かったかもしれません。

beginner07
質問者

補足

少し補足させていただきます。 まず、人間対人間でやった場合、問題なくプログラムは動きます。 また、人間対コンピュータでやった場合、p[]を大域変数にすると問題なく動くのですが、 局所変数にした場合、5,6手打った後にセグメンテーションエラーで終了してしまいます。 最後に、パスについては、別の関数で判定できるようにしているのでおそらく問題ないと思います。

  • maku_x
  • ベストアンサー率44% (164/371)
回答No.3

Position p[]; を、関数 computer() 内の自動変数にすると、関数 computer() が呼び出される度に記憶領域 p[] が割り当てられ、computer() の処理終了時に記憶領域 p[] が解放されるので、結果的に盤面の内容を覚えていないことになります。記憶領域 p[] が解放された後は、p[] の内容は何が入っているのか分かりません。こうなると、どのような不具合が生じるかは予想できません。なので、自動変数にするなら、プログラムの起動時(main()内とかで)に記憶領域 p[] を確保し、プログラム動作中はその内容を保持し続けるようなコーディングにする必要があります。

beginner07
質問者

お礼

回答ありがとうございます。 確かに自動領域の開放については良く考えていませんでした。 しかし、今回は盤面の内容はboard[][]に覚えさせていて、p[]は石を置ける場所を一時的に記憶するためにだけ使っているので大丈夫だと思います。

  • Tacosan
  • ベストアンサー率23% (3656/15482)
回答No.2

count_turn_over の中で, p.dr とか p.dc をチェックしてみたら?

beginner07
質問者

お礼

回答ありがとうございます。 チェックしてみましたが、特に問題はないようでした。 ところで、find_legal_moveからis_legal_move,count_turn_overと関数を呼び出していくと、 繰り返し処理が500回以上になってしまいます。 これが何か原因になっていないでしょうか?

noname#98978
noname#98978
回答No.1

>セグメンテーション違反になってしまいます。 >原因を教えていただけないでしょうか。 不正なアドレスに書き込みなどしているのが原因です。

beginner07
質問者

お礼

回答ありがとうございます。 勉強になりました。

関連するQ&A

  • コンパイルするとエラーに。C言語(改め)

    インクルード 定義 メイン関数 エラー内容 が収まりませんでした; (長すぎてどうすればよいのやら;) int readlines(char *lineptr[], int maxlines) { int len, nlines; char *p, line[MAXLEN]; nlines = 0; while ((len = getline(line, MAXLEN)) > 0) if (nlines >= maxlines || (p = alloc(len)) == NULL) return -1; else { line[len-1] = '\0'; strcpy(p, line); lineptr[nlines++] = p; } return nlines; } char *alloc(int n) { if (allocbuf + ALLOCSIZE - allocp >= n) { allocp += n; return allocp - n; } else return 0; } void kr_qsort(char *v[], int left, int right, int (*comp)(void *, void *)) { int i, last; void swap(char *v[], int i, int j); if (left >= right) return; swap(v, left, (left + right)/2); last = left; for (i = left+1; i <= right; i++) if ((*comp)(v[i], v[left]) < 0) swap(v, ++last, i); swap(v, left, last); kr_qsort(v, left, last-1, comp); kr_qsort(v, last+1, right, comp); } void swap(char *v[], int i, int j) { char *temp; temp = v[i]; v[i] = v[j]; v[j] = temp; } void readargs(int argc, char *argv[]) { char c; int atoi(char *); while (--argc > 0 && (c = (*++argv)[0] == '-' || c == '+') { if (c == '-' && !isdigit(*(argv[0]+1))) while (c = *++argv[0]) switch (c) { case 'd': option |= DIR; break; case 'f': option |= FOLD; break; case 'n': option |= NUMERIC; break; case 'r': option |= DECR; break; default: printf("sort: illegal option %c\n", c); error("Usage: sort -dfnr [+pos1] [-pos2]"); break; } else if (c == '-') pos2 = atoi(argv[0]+1); else if ((pos1 = atoi(argv[0]+1)) < 0) error("Usage: sort -dfnr [+pos1] [-pos2]"); } if (argc || pos1 > pos2) error("Usage: sort -dfnr [+pos1] [-pos2]"); } } void writelines(char *lineptr[], int nlines, int order) { int i; if (order) for (i = nlines-1; i >= 0; i--) printf("%s\n", lineptr[i]); else for (i = 0; i < nlines; i++) printf("%s\n", lineptr[i]); } int charcmp(char *s, char *t) { char a, b; int i, j, endpos; int option, pos1, pos2; int fold = (option & FOLD) ? 1 : 0; int dir = (option & DIR) ? 1 : 0; i = j = pos1; if (pos2 > 0) endpos = pos2; else if ((endpos = strlen(s)) > strlen(t)) endpos = strlen(t); do { if (dir) { while (i < endpos && !isalnum(s[i]) && s[i] != ' ' && s[i] != '\0') i++; while (j < endpos && !isalnum(t[j]) && t[j] != ' ' && t[j] != '\0') j++; } if (i < endpos && j < endpos) { a = fold ? tolower(s[i]) : s[i]; i++; b = fold ? tolower(t[j]) : t[j]; j++; if (a == b && a == '\0') return 0; } } while (a == b && i < endpos && j < endpos); return a - b; } int numcmp(char *s1, char *s2) { double v1, v2; char str[MAXSTR]; substr(s1, str, MAXSTR); v1 = atof(str); substr(s2, str, MAXSTR); v2 = atof(str); if (v1 < v2) return -1; else if (v1 > v2) return 1; else return 0; } void substr(char *s, char *str, int maxstr) { int i, j, len; extern int pos1, pos2; len = strlen(s); if (pos2 > 0 && len > pos2) len = pos2; else if (pos2 > 0 && len > pos2) error("substr: string too short"); for (j = 0, i = pos1; i < len; i++, j++) str[j] = s[i]; str[j] = '\0'; } int getline (char s[], int lim) { int c, i; i = 0; while (--lim > 0 && (c=getchar()) != EOF && c != '\n') s[i++] = c; if (c == '\n') s[i++] = c; s[i] = '\0'; return i; } void error(char *s) { printf("%s\n", s); exit(1); }

  • エラーの原因が分かりません "undefined reference to"

    ライブラリのヘッダファイル matrix.h #ifndef MATRIX_H #define MATRIX_H #ifdef __cplusplus extern "C"{ #endif typedef struct{ int row,col; double *elements; } MATRIX; extern int matrix_error_code; extern void zero_matrix(MATRIX *a); extern void identity_matrix(MATRIX *a); extern void show_matrix(MATRIX *x); extern MATRIX multiply_matrix(MATRIX *a,MATRIX *b); extern MATRIX transposed_matrix(MATRIX *a); #ifdef __cplusplus } #endif #endif ライブラリのソースファイル matrix.c #include <stdio.h> #include <stdlib.h> #include <math.h> #include "matrix.h" int matrix_error_code = 0; void zero_matrix(MATRIX *a) { int i,size; double *p; size=a->row*a->col; if((p = malloc(sizeof(double)*size)) == NULL) { puts("メモリを確保できません."); exit(0); } a->elements=p; for(i=0;i<size;i++) *p++=0; } void identity_matrix(MATRIX *a) { int i; zero_matrix(a); for(i=0;i<a->row;i++) { *(a->elements+i*a->col+i)=1.0000; } } void show_matrix(MATRIX *x) { int i,j; for(i=0;i<x->row;i++) { for(j=0;j<x->col;j++) { printf("%3.4lf ",*(x->elements+i*x->col+j)); } printf("\n"); } printf("\n"); } MATRIX transposed_matrix(MATRIX *a) { MATRIX x; int i,j; double *p; if((p = malloc(sizeof(double)*(a->row*a->col))) == NULL) { puts("メモリを確保できません."); exit(0); } x.elements=p; x.row=a->col; x.col=a->row; for(i=0;i<x.row;i++) { for(j=0;j<x.col;j++) { *p++=*(a->elements+j*x.row+i); } } return x; } MATRIX multiply_matrix(MATRIX *a,MATRIX *b) { int i,j,k; double *p; MATRIX x; x.row=a->row; x.col=b->col; if((p = malloc(sizeof(double)*(x.row*x.col))) == NULL) { puts("メモリを確保できません."); exit(0); } x.elements=p; for(i=0;i<x.row;i++) { for(j=0;j<x.col;j++) { for(k=0;k<a->col;k++) { *p += *(a->elements+i*a->col+k) * *(b->elements+k*b->row+j); } } p++; } return x; } 動作確認のアプリケーションファイル test_matrix.c #include <stdio.h> #include "matrix.h" int main(void) { int i,j; MATRIX b,c,d,f; b.row=c.row=2; b.col=c.col=2; identity_matrix(&b); identity_matrix(&c); d=transposed_matrix(&b); show_matrix(&d); f=multiply_matrix(&b,&c); show_matrix(&f); return 0; } ライブラリのコンパイルまではエラーなしで出来るのですが、test_matrix.cをコンパイルすると、"undefined reference to '_transposed_matrix'"と、"undefined reference to '_multiply_matrix'"の2つが表示されてコンパイルができません。 どうかよろしくお願いします。

  • 自作の行列クラスを継承するさいにエラーがでます

    現在、c++の学習で、自作の基底行列クラスMatrixを作成し、このクラスを継承して新たにlduMatrixを作成する事を考えています。 が、継承し、 lduMatrix a( 3, 3); a = 3; とすると、 main.C:13: warning: passing ‘double’ for argument 1 to ‘lduMatrix::lduMatrix(int)’ というエラーがでてコンパイルできずにいます。その一方で、 lduMatrix a(3,3, 3.14); とするとコンパイルはとおり、lduMatrix行列の各要素(a[1][1]など)の値をプリントさせると、[[3.14]]の値が入っていることを確認しております。 どこが間違っているのか御指導いただけると幸いです。 以下、クラスの中身です。よろしくおねがいします。 《Class: Matrix》 #include <iostream> class Matrix{ private: //! Size of row and column in Matrix int row_, col_; //! Row pointers double** m_; //! Allocate function for row-pointers void allocate(); public: Matrix(); //! Constructor with given matrix size Matrix( const int, const int ); //! Constructor with given matrix size and value fro all elements Matrix( const int, const int, const double ); //! Destructor ~Matrix(); ・・・省略・・・ double* operator[]( const int ); double* operator[]( const int ) const ; void operator=( const double ); }; /* Private functions *********************************************** */ void Matrix::allocate() { m_ = new double* [row_]; m_[0] = new double [row_*col_]; for ( int i=1; i<row_; i++ ){ m_[i] = m_[i-1] + col_; } } /* Destructor ****************************************************** */ Matrix::~Matrix(){ delete[] m_[0]; delete[] m_; } /* Constructors **************************************************** */ // NULL constructor Matrix::Matrix() : row_(0), col_(0), m_(NULL) {} // Constructor with given matrix size Matrix::Matrix( const int row, const int col ) : row_(row), col_(col) { allocate(); } // Constructor with given matrix size and value for all elements Matrix::Matrix( const int row, const int col, const double s ): row_(row), col_(col) { allocate(); double* m = m_[0]; for ( int i=0; i<row_*col_; i++ ){ m[i] = s; } } 《省略》 /* Member operators ************************************************ */ double* Matrix::operator[]( const int i ){ return m_[i]; } void Matrix::operator=( const double t ){ double* m = m_[0]; int nm = row_*col_; for ( int i=0; i<nm; i++ ) { m[i] = t; } } 《Class: lduMatrix》 class lduMatrix : public Matrix{ public: lduMatrix(); lduMatrix( const int ); lduMatrix( const int, const double ); }; lduMatrix::lduMatrix() {} lduMatrix::lduMatrix( const int mSize ) : Matrix( mSize, mSize, 0.0 ) {} lduMatrix::lduMatrix( const int mSize, const double s ) : Matrix( mSize, mSize, s ) {}

  • for文について【ID3タグ取得のプログラム】

    ID3タグ取得のプログラムなのですがちゃんと動いたのは良いんですが解らないプログラム部分がありました。 ググったり過去の質問探したりしたのですが解答が見つかりません。 お手数ではありますがご教授願います。 以下はプログラムです。 /*ID3タグ取得プログラム*/ import java.io.*; import java.nio.channels.*; import java.util.Arrays; class TagInfo{ final private String name; final private int pos; final private int len; public TagInfo(String name,int pos,int len){ this.name=name; this.pos=pos; this.len=len; } public String getName() { return name; } public int getPos() { return pos; } public int getLen() { return len; } } public class M_data { private static byte[] copyOfRange(byte b[],int pos, int len){ byte[] a=new byte[len]; System.arraycopy(b,pos,a,0,len); return a; // return java.util.Arrays.copyOfRange(b,pos,pos+len); } static void music() throws IOException{ File file = new File("C:/music/music4.mp3"); FileInputStream fis=new FileInputStream(file); String charsetName="Shift_JIS"; //if(1<args.length) charsetName=args[1]; FileChannel fc=fis.getChannel(); fc.position(fc.size()-128); byte[] b=new byte[128]; if(fis.read(b)==128 && b[0]=='T' && b[1]=='A' && b[2]=='G'){ TagInfo[] infos={new TagInfo("Song title:",3,30),new TagInfo("Artist:",33,30), new TagInfo("Album:",63,30),new TagInfo("Year:",93,4), new TagInfo("Comment:",97,30),new TagInfo("Genre:",127,1) }; int i=0; /*以下のfor文です*/ for(TagInfo info: infos){ System.out.print(i + info.getName()); System.out.println(new String(copyOfRange(b,info.getPos(),info.getLen()),charsetName)); i++; } } } public static void main(String[] args) throws IOException{ music(); } }

    • ベストアンサー
    • Java
  • データ構造・15パズル・Algebra

    通信大学で、データ構造を専攻中なのですが、 添付した画像部分が具体的に何を意味しているのかよく分かりません。 {(Ptile, blank), (Pblank, t)} ∪{(p',t') | (p',t') ∈ b ∧ p' ∉ {Ptile, Pblank}} この(p',t')は何を表しているんでしょうか。どうぞ宜しくお願い致します。 ----------------------------- Algebra puzzle 15 sorts tile, position, board, bool ops init: tile16 -> board move: board x tile -> board solved: board -> bool pos: board x tile -> position sets tile = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,blank} position = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,error} board = {c ⊂ (position \ {error}) x tile |c| = 16 ∧∀c = (p,t) ∈ c: c’ ≠ c -> p‘ ≠ p ∧ t‘ ≠ t } ∪ {error}

  • プログラムからメソッドを呼び出したいのですが

    今、ArtName.javaのプログラムにM_data.javaのプログラム内のメッソドを呼び出したいのですがコンパイルするとエラーになってしまいます。どのように記述すればメッソドを呼び出すことができるかご教授お願いたします。 以下がプログラムになります。 /*ArtName.java*/ import java.io.*; import java.nio.channels.*; import java.util.Arrays; class ArtName{ public static void an(String[] arg){ int i,j,number,song; char artname[]=new char[song]; M_data.music(); number=1; for(i=0;i<song;i++){ for(j=0;j<song;j++){ if(TagInfo[i]!=TagInfo[j]){ number++; } } } } } /*M_data.java*/ import java.io.*; import java.nio.channels.*; import java.util.Arrays; class TagInfo{ final private String name; final private int pos; final private int len; public TagInfo(String name,int pos,int len){ this.name=name; this.pos=pos; this.len=len; } public String getName() { return name; } public int getPos() { return pos; } public int getLen() { return len; } } public class M_data { private static byte[] copyOfRange(byte b[],int pos, int len){ byte[] a=new byte[len]; System.arraycopy(b,pos,a,0,len); return a; // return java.util.Arrays.copyOfRange(b,pos,pos+len); } static void music() { File file = new File("C:/Users/NEC-PCuser/Downloads/ Answer .mp3"); FileInputStream fis=new FileInputStream(file); String charsetName="Shift_JIS"; //if(1<args.length) charsetName=args[1]; FileChannel fc=fis.getChannel(); fc.position(fc.size()-128); byte[] b=new byte[128]; if(fis.read(b)==128 && b[0]=='T' && b[1]=='A' && b[2]=='G'){ TagInfo[] infos={new TagInfo("Song title:",3,30),new TagInfo ("Artist:",33,30)}; int i=0; /*以下のfor文です*/ for(TagInfo info: infos){ System.out.print(i + info.getName()); System.out.println(new String(copyOfRange(b,info.getPos (),info.getLen()),charsetName)); i++; } } } public static void main(String[] args) throws IOException{ music(); } } ArtName.javaをコンパイルすると Artname.java:17シンボルが見つかりません。 シンボル:ArtNameのクラス        if(TagInfo[i]!=TagInfo[j]{ とエラーになります。どのように記述すればコンパイルできるかお教えてください。 よろしくお願いいたします。

  • プログラムからメソッドを呼び出したいのですが

    今、ArtName.javaのプログラムにM_data.javaのプログラム内のメッソドを呼び出したいのですがコンパイルするとエラーになってしまいます。どのように記述すればメッソドを呼び出すことができるかご教授お願いたします。 以下がプログラムになります。 /*ArtName.java*/ import java.io.*; import java.nio.channels.*; import java.util.Arrays; class ArtName{ public static void an(String[] arg){ int i,j,number,song; char artname[]=new char[song]; M_data.music(); number=1; for(i=0;i<song;i++){ for(j=0;j<song;j++){ if(TagInfo[i]!=TagInfo[j]){ number++; } } } } } /*M_data.java*/ import java.io.*; import java.nio.channels.*; import java.util.Arrays; class TagInfo{ final private String name; final private int pos; final private int len; public TagInfo(String name,int pos,int len){ this.name=name; this.pos=pos; this.len=len; } public String getName() { return name; } public int getPos() { return pos; } public int getLen() { return len; } } public class M_data { private static byte[] copyOfRange(byte b[],int pos, int len){ byte[] a=new byte[len]; System.arraycopy(b,pos,a,0,len); return a; // return java.util.Arrays.copyOfRange(b,pos,pos+len); } static void music() { File file = new File("C:/Users/NEC-PCuser/Downloads/ Answer .mp3"); FileInputStream fis=new FileInputStream(file); String charsetName="Shift_JIS"; //if(1<args.length) charsetName=args[1]; FileChannel fc=fis.getChannel(); fc.position(fc.size()-128); byte[] b=new byte[128]; if(fis.read(b)==128 && b[0]=='T' && b[1]=='A' && b[2]=='G'){ TagInfo[] infos={new TagInfo("Song title:",3,30),new TagInfo ("Artist:",33,30)}; int i=0; /*以下のfor文です*/ for(TagInfo info: infos){ System.out.print(i + info.getName()); System.out.println(new String(copyOfRange(b,info.getPos (),info.getLen()),charsetName)); i++; } } } public static void main(String[] args) throws IOException{ music(); } } ArtName.javaをコンパイルすると Artname.java:17シンボルが見つかりません。 シンボル:ArtNameのクラス        if(TagInfo[i]!=TagInfo[j]{ とエラーになります。どのように記述すればコンパイルできるかお教えてください。 よろしくお願いいたします。

    • ベストアンサー
    • Java
  • C++のプログラムのエラー原因のアドバイスお願いします。

    C++のソース内でエラーがでます。 エラー箇所は以下の関数内の最初と最後のflagに対する処理部分です。 ★マークをつけた部分が違うのかと思うのですが、 他人のプログラムなのでどこをどう直せばいいかわかりません。 処理部分ではflag[i][j]なのに宣言が★になる意味もわかりません・・・。new,deleteはこれで大丈夫なのかとか。 どなたかアドバイスお願いします。 環境:visual studio.NET, windowsXP 関数 { register int i, j; int row,col; bool **flag = new bool *[row+2];//★ for (i = 0; i < row+2; i++) flag[i] = new bool[col+2];//★ num_feature_point = 0; for (i = 0; i < row+2; i++) {  for (j = 0; j < col+2; j++) { /*/*ここからflag[i][j] = false; などの処理が数行*/*/ for (i = 0; i < row+2; i++) delete [] flag[i]; delete [] flag; }

  • 文字列の配列の比較

    こんにちは。タイトルどおり簡単な質問なのですが、どうしても確認したいのでお願いします。 とあるメソッドで、2次元配列の中にいくつか大文字のOが入ってるのですが、与えられた配列にOがあればtrueを返し、なければfalseを返します。 public boolean cellAt(int row, int col){ if(space[row][col].equals("O")) return true; else return false; } rowとcolはテストメソッドから値を受け取ります。 これでプログラム自体は動くのですが、WebCatという自動的に採点するものがあるのですが、それによるとエラーがでてしまいます・・・。 どこが違うのかは教えてくれないのですが・・・。 上で間違っているとすれば、文字列の比較くらいしかないんじゃないかと思うのですが、 space[row][col].equals("O") これで比較できますよね? 他のを調べて、if (Arrays.equals(space[row][col], "O"))これを試してもみたのですが、赤線が出てしまって無理でした。 どなたか宜しくお願いします。

  • java

    java プログラミングで3×3の○×ゲームを作りたいのですが、エラーが出てしまいます。 どこに問題があるかわかりません。 教えていただけたら嬉しいです。 長くなってしまいますが、ご了承ください(コメント一部略)。 import java.io.*; // マスにの中身が // 空白: 0 // O : 1 // X : 2 class ox { // 勝敗の判定をするメソッド // 勝敗が付いていなければ0 を // O の勝ちなら1 を // X の勝ちなら2 を // 引き分けなら-1 を // それぞれ返す。 static int judge( int board[][] ) { int i, j, flag; for( i = 0; i < 3; ++i ) { flag = 1 | 2; for( j = 0; j < 3; ++j ) flag &= board[j][i]; // <=> flag = flag & board[j][i] if( flag != 0 ) return flag; } // 縦の列を調べる for( i = 0; i < 3; ++i ) { flag = 1 | 2; for( j = 0; j < 3; ++j ) flag &= board[i][j]; if( flag != 0 ) return flag; } // 左上→右下のナナメ flag = 1 | 2; for( j = 0; j < 3; ++j ) flag &= board[j][j]; if( flag != 0 ) return flag; // 右上→左下のナナメ flag = 1 | 2; for( j = 0; j < 3; ++j ) flag &= board[2-j][j]; if( flag != 0 ) return flag; // まだ置けるマスがあるかの判定 flag = 1; for( i = 0; i < 3; ++i ) { for( j = 0; j < 3; ++j ) flag *= board[i][j]; } // flag != 0 ってことは、置けるマスは無い→勝負が付いた // どちらかが勝ったのなら、上でreturn しているはず // ということで、引き分け if( flag != 0 ) return -1; // 何事もなければ、勝負続行 return 0; } // 番面の様子を表示するメソッド static void show ( int board[][] ) { String display = ""; String masu[] = { " ", "O", "X" }; int i; display += " |1|2|3\n"; for( i = 0; i < 3; ++i ) { display += "-+-+-+-\n"; display += (i+1) + "|" + masu[board[0][i]] + "|" + masu[board[1][i]] + "|" + masu[board[2} System.out.println( display ); } static int isreach( int three[], int turn ) { int i, result; // 各マスの値を2 乗して足し合わせる result = 0; for( i=0; i<3; ++i ) result += three[i]*three[i]; // リーチなら、下の条件を満たすはず if( result == 2*turn*turn ) { for( i=0; i<3; ++i ) if( three[i] == 0 ) break; return i; } return -1; } static int rival( int board[][] ) { int x,y,i,j,n; int three[] = new int[3]; // x, y が未定である事を明示 for( i=0; i<3; ++i ) { for( j=0; j<3; ++j ) three[j] = board[j][i]; 続きは追記にて