変数への参照を変更する関数を呼び出そうとしていますが、プログラムを実行するたびに不正なアクセスが続いています。C++でポインターと参照に問題がある
私はこれを理解できないようです#include "calculations.hpp"
#include <iostream>
using namespace std;
void calculate(string nameOfFood, int *numberOfServings, int *calories, float *fatInGrams, float *carbsInGrams, float *fiberInGrams, float *proteinInGrams){
*numberOfServings = 24;
*calories = 15;
}
、私はそれができる知っている
#ifndef calculations_hpp
#define calculations_hpp
#include <stdio.h>
#include <iostream>
using namespace std;
void calculate(string nameOfFood, int *numberOfServings, int *calories, float *fatInGrams, float *carbsInGrams, float *fiberInGrams, float *proteinInGrams);
#endif /* calculations_hpp */
と計算関数ファイル:
#include <iostream>
#include <fstream>
#include "calculations.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
char input[12];
string input2;
string nameOfFood;
int *numberOfServings = 0;// THIS IS WHERE I KEEP GETTING THE BAD ACCESS
int *calories = 0;
float *fatInGrams = 0;
float *carbsInGrams = 0;
float *fiberInGrams = 0;
float *proteinInGrams = 0;
int count = 0;
// Open an output file
ofstream outData; //IGNORE
// Start a loop
for(int i = 0; i<5; i++){
// On the console, ask if the user ate. If the answer is No, be creative, but polite in your answer.
cout << "did you eat? yes or no" << endl;
cin >> input;
if (input[0] == 'y'){
cout << "Please enter the name; number of servings; calories; amount of fat";
cout << "; number of carbs; amount of fiber; and the amount of protein" << endl;
cin >> nameOfFood
>> *numberOfServings
>> *calories
>> *fatInGrams
>> *carbsInGrams
>> *fiberInGrams
>> *proteinInGrams;
calculate(nameOfFood, numberOfServings, calories, fatInGrams,carbsInGrams, fiberInGrams, proteinInGrams);
i = 0;
count++;
}
if (input[0] == 'n'){
i = 5;
}
}
cout << count << endl;
cout << "calories is " << &calories << endl;
cout << "number of servings is " << &numberOfServings << endl;
計算機能はのヘッダファイルを持っています私がObjective-Cのクラスでこれまでに見たことがあれば、どんな助けもありがたいです。ありがとうございました。
に類似の修正が単にポインタの使用を停止してください。コードからすべてのポインタを削除します。そこは、それだけです。 :) –