2017-07-20 19 views
-1

は、私は私のコードで問題を抱えているが、私はラインセグメンテーションフォルト11なぜですか?

#include <stdio.h> 
#include "VectorMath.h" 

int getUserInput() { 
    int userinput; 

    printf("1) Calculating new vector and distance \n"); 
    printf("0) Exit \n"); 

    scanf("%d", &userinput); 

    return userinput; 
} 

void getUserPoint(int vector[3]) { 
    int userinput; 
    char coordinate[] = {'x', 'y', 'z'}; 
    int counter = 0; 

    for(counter = 0; counter < 3; counter++){ 
     printf("%c", coordinate[counter]); 
     scanf("%d", &userinput); 
     vector[counter] = userinput; 
    } 
} 


int main() { 
    int vectorA[3]; 
    int vectorB[3]; 

    int input = 0; 
    int counter = 0; 

    int *p_result; 

    double result; 

    _Bool run = 1; 

    while(run) { 
     input = getUserInput(); 

     if (input == 1){ 
      printf("Enter point A (x,y,z) \n"); 
      getUserPoint(vectorA); 
      printf("Enter point B (x,y,z) \n"); 
      getUserPoint(vectorB); 
     }else if(input == 0) { 
      break; 
     } 

     result = distance(vectorA, vectorB, p_result); 

     printf("The distance between the points A and B is %.2lf \n", result); 
     printf("The vector between the point A and B is \n"); 
     for (counter = 0; counter < 3; counter++){ 
      printf("%d \n", p_result[counter]); 
     } 
    } 

    return 0; 
} 

これがメインMethodeのある中で11エラーが発生したセグメンテーションフォールトを取得する理由を私は知りません。このエラーは、forループの後(または内部)に発生します。ポインタは、この.cファイルに初期化される:

#include "VectorMath.h" 
#include <math.h> 

double distance(int pointA[3], int pointB[3], int *p_result) { 
    double distance_result; 
    int vectorbtw[3]; 
    int counter = 0; 

    for(counter = 0; counter < 3; counter++) { 
     vectorbtw[counter] = pointB[counter] - pointA[counter]; 
    } 

    p_result = vectorbtw; 

    for(counter = 0; counter < 3; counter++) { 
     distance_result += pow(vectorbtw[counter], 2); 
    } 

    distance_result = sqrt(distance_result); 

    return distance_result; 
} 

そして、これはheadderです:ロングコード用

#ifndef VectorMath_h 
#define VectorMath_h 
    double distance(int pointA[3], int pointB[3], int *p_result); 
#endif 

申し訳ありませんが、私は、あなたが全体のコードが必要になりますと思いました。 私は言ったように、なぜp_resultポインタが他の.cファイルで初期化され、配列の先頭を指しているのかわかりません。

EDIT:これは、2点間の距離を計算し、2点間の距離とベクトルを返す関数を持っているということです。それがp_resultポインタを使っている理由です。

+0

'p_result'はルーチンによって変更されません。 –

答えて

0

どこでもint *p_result;を初期化しません。あなたは距離ルーチンへのユニット化されたポインタの値を渡しています。そのローカルコピーはローカル配列をポイントするように設定されていますが、その関数呼び出しの後にメイン関数のp_resultはまだ初期化されていません。

0

p_resultポインタが有効なメモリを指すように必要、配列、その代わりに

int *p_result; 

使用

int p_result[3]; 

と変わらず、残りを残すの例については、それは動作したのですか?

distance()関数は、p_resultが既に有効なポインタであると仮定していますが、それは真であるため、どこかを指す必要があります。それがあるとして、それはどこにも向いていない、それが初期化されていないですので、あなたも、私はあなたがポイントこの方法をご覧になりました願っています。この

int result[3]; 
int *p_result; 

p_result = result; 

のようにそれを行うことができます。

+0

私はセグメンテーションフォルトを解決しましたが、私はちょうどゼロを与えますが、あなたとhttps://stackoverflow.com/users/1813336/cleblancが私の質問に感謝しました。 – nCap

関連する問題