나는 C로 프로그램을 만들고 있는데, 나는 메모리에 약간의 문제가 있다고 생각한다.C - 구조체 문제 - 쓰기
내 문제는 : 구조체를 반환하는 2 함수가 있습니다. 한 번에 하나의 함수 만 실행하면 아무런 문제가 없습니다. 하지만 하나씩 실행하면 두 번째 구조체에 writting 할 때 항상 오류가 발생합니다.
기능 struct item* ReadFileBIN(char *name)
- 이진 파일을 읽습니다. struct tables* getMesasInfo(char* Filename)
- 텍스트 파일을 읽습니다.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int numberOfTables=0;
int numberOfItems=0;
//struct tables* mesas;
//struct item* Menu;
typedef struct item{
char nome[100];
int id;
float preco;
};
typedef struct tables{
int id;
int capacity;
bool inUse;
};
struct tables* getMesasInfo(char* Filename){
struct tables* mesas;
char *c;
int counter,numberOflines=0,temp=0;
char *filename=Filename;
FILE * G;
G = fopen(filename,"r");
if (G==NULL){
printf("Cannot open file.\n");
}
else{
while (!feof(G)){
fscanf(G, "%s", &c);
numberOflines++;
}
fclose(G);
}
/* Memory allocate for input array */
mesas = (struct tables *)malloc(numberOflines* sizeof(struct tables*));
counter=0;
G=fopen(filename,"r");
while (!feof(G)){
mesas[counter].id=counter;
fscanf(G, "%d", &mesas[counter].capacity);
mesas[counter].inUse= false;
counter++;
}
fclose(G);
numberOfTables = counter;
return mesas;
}
struct item* ReadFileBIN(char *name)
{
int total=0;
int counter;
FILE *ptr_myfile;
struct item my_record;
struct item* Menu;
ptr_myfile=fopen(name,"r");
if (!ptr_myfile)
{
printf("Unable to open file!");
}
while (!feof(ptr_myfile)){
fread(&my_record,sizeof(struct item),1,ptr_myfile);
total=total+1;
}
numberOfItems=total-1;
Menu = (struct item *)calloc(numberOfItems , sizeof(struct item));
fseek(ptr_myfile, sizeof(struct item), SEEK_END);
rewind(ptr_myfile);
for (counter=1; counter < total ; counter++)
{
fread(&my_record,sizeof(struct item),1,ptr_myfile);
Menu[counter] = my_record;
printf("Nome: %s\n",Menu[counter].nome);
printf("ID: %d\n",Menu[counter].id);
printf("Preco: %f\n",Menu[counter].preco);
}
fclose(ptr_myfile);
return Menu;
}
int _tmain(int argc, _TCHAR* argv[])
{
struct item* tt = ReadFileBIN("menu.dat");
struct tables* t = getMesasInfo("Capacity.txt");
getchar();
}**
점점 메신저 오류는 다음과 같습니다 :
"0x00411700에 처리되지 않은 예외 TEST.EXE의 :가 0xc0000005 :. 액세스 위반 쓰기 위치를 0x00000000"
내 코드는 이것이다 "Menu [counter] = my_record;"에서
미리 감사드립니다.
:. 당신이 구조체의 배열에 대한 할당하고 기억하고 당신이 할당되도록 메사는, 첫 번째 요소에 대한 포인터입니다.? 그 위치에서 numberoflines 구조체를위한 메모리. 이 문제를 해결하고 다시 실행하면 우리가 볼 수 있습니다. –