かなり大きなコードに問題があります。自分自身を知って、それは何らかの愚かな間違い、または、可能性が高い、ポインタの理解の欠如です。私は本当に助けが必要です。誰かがそれを見ることができたら、私はとても感謝しています!私は今それを説明するつもりです。C - 構造体の動的配列
私のプログラミングクラスのプログラムです。教師はtxtファイルで数字(N)と文字(X)を与え、3つのフィールド(int、char、float)と4つの関数を持つ構造を作成したいと考えています。
function#1数Nを引数とし、N個の構造体へのポインタの配列に動的にメモリを割り当てます。構造体のフィールドに値を割り当てます。intとcharはランダムな値に設定され、floatフィールドは構造体の番号に設定されます。この関数は配列のアドレスを返します。
function#2は、作成された配列(その中のポインタの数)とその配列へのポインタを引数として取り、その配列を削除してメモリを解放します。
機能#3は、引数として配列に作成された配列とポインタのサイズを取得し、その後、int型のフィールドに基づいて構造をソート、バブルソート
機能#4の構造を検索し、カウントを使用して構造体のcharフィールドで文字(X)が何回繰り返されるかを指定します。
ここにコメントとエラーのコードがあります。私が間違っていることを説明できる人はいますか?正直言って私はほとんど時間外ですが、私はこれを理解し解決するために一晩中起きています。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
struct Foo {
int fieldint;
char fieldchar;
float fieldfloat;
};
Foo *initialize(int N);
int sort(int N, Foo *tablica);
int count(int N, Foo *tablica, char*X);
int deleting(int N, Foo **tablica);
int main() {
//this reads the number N and the letter to find from the .txt file:
FILE *file = fopen("inlab01.txt", "r");
int number;
char letter[1];
if (file == NULL) {
printf("Error opening file");
exit(-1);
}
while (fscanf(file, "%d%s", &number, letter) != EOF);
fclose(file);
//creating the array
//again, it's supposed to be an array of pointers to N structures:
Foo *arr[number];
*arr = initialize(number);
//sorting:
sort(number, *arr); //the program crashes at this function
//counting how many times the given letter appears:
//count(number, *arr, letter);
//we're supposed to print the first 20 of the structures
//this loop prints one structure and then the program crashes
for(int i=0;i<20;i++) {
printf("Structure %d:\nfield int:%d\nfield char:%c\nfield float:\f\n\n", i+1, arr[i]->fieldint, arr[i]->fieldchar, arr[i]->fieldfloat);
}
//deleting:
deleting(number, arr);
getch();
return 0;
}
Foo *initialize(int N) {
Foo **array;
array = (Foo **)malloc(sizeof(Foo) * N);
srand(time(NULL));
for(int i=0; i<N; i++) {
array[i] = (Foo*)malloc(sizeof(Foo));
array[i] -> fieldint = rand(); //random number
array[i] -> fieldchar = (char)(rand() % 24) + 65; //random letter
array[i] -> fieldfloat=i;
}
return *array;
}
int sort(int N, Foo *array) {
int temp;
for (int i=0;i<N;i++){
for (int j=N-1;j>=j;j--) {
if(array[j].fieldint < array[j-1].fieldint) {
temp = array[j-1].fieldint;
array[j-1].fieldint = array[j].fieldint;
array[j].fieldint = temp;
}
}
}
return 0;
}
int count(int N, Foo *array, char*X){
int counter = 0;
for(int i=0;i<N;i++) {
if (array[i].fieldchar == 'X') {
counter = counter+1;
}
}
return counter;
}
int deleting(int N, Foo **array) {
for (int i=0;i<N;i++) {
free(array[i]);
}
free(array);
return 0;
}
すべてがコンパイルされますが、実際に何かを実行する代わりにプログラムがクラッシュします。
助けてください。
あなたが直面しているエラーを示す、最小限で完全で検証可能な例を投稿してください。今のところあなたの質問はTLです; DR材料とほとんどの人は気にしません。 – DeiDei
あなたのコードはコンパイルされません。たとえば、 '* arr = initialize'は間違っています、' arr [i] - > fieldint'は間違っています。 –
ところで、あなたはC++でCコードをコンパイルしているようですが、おそらくあなたは* .cpp拡張子を使用しています。 –