【发布时间】:2016-01-08 19:06:01
【问题描述】:
我有一个与本学期的编程项目有关的问题。 我有一个具有结构的动态数组,该结构包含一个字符串的参数。问题是我需要将该字符串从静态更改为动态。 我已经编写了请求字符串并将其存储在动态数组中然后返回的函数。 稍后在程序中,我需要将数组(存储动态字符串)中的信息写入二进制文件。 我怎样才能做到这一点,我怎样才能知道何时以及如何正确释放该动态字符串的内存? 如果我释放了存储字符串的数组,我是否也释放了存储字符串本身的内存?
我的数组将存储字符串:
inspections *inspectionsArray;
char* dynamicString(){
char *stringPointer = NULL,*paux = NULL, char;
int stringSize = 1,stringEnd = 0,i;
stringPointer = (char*)malloc(sizeof(char));
if (stringPointer == NULL) {
printf("\nError alocating memory");
}else{
printf("\nEnter String: ");
while (char != EOF && char != '\n') {
char = getc(stdin); //Obter o char do stding
paux = realloc(stringPointer, stringSize*sizeof(char));
if (paux != NULL) {
stringPointer = paux;
stringPointer[stringEnd] = char; //meter o char na string
stringSize++; //incrementar o tamanho da string
stringEnd++;
}else{
printf("\nErro a realocar memoria para a string");
}
}
stringPointer[stringEnd] = '\0';
printf("\nString: %s", stringPointer);
}
return stringPointer;
}
我将在其中存储字符串的结构。
typedef struct
{
//A bunch of parameters in here
char *dynamicString;
} inspection;
enter code here
我用来将数据存储到数组的函数:
inspectionArray* registerInspection(inspection *inspectionArray){
char *string;
//I removed a bunch of code to not confuse things
string = dynamicString;
return inspection;
}
文件保存功能:
void saveBinaryFile(inspection *inspections, int inspectionCounter)
{
FILE * inspectionArrayFile;
fileInspections = fopen("inspections.dat","wb");
if (fileInspections == NULL)
{
perror("\nError opening the file");
}
else
{
fwrite(&inspectionCounter, sizeof (int), 1, inspectionArrayFile);
fwrite(inspections, sizeof(tipoVeiculo), inspectionCounter, inspectionArrayFile);
// I write a bunch of stuff and verify it properly
fclose(inspectionArrayFile);
}
}
如何正确读取和释放字符串?
我试过这个:
void freeArrayStrings(inspections *inspectionsArray,int counter){
int i;
for (i=0; i<counter; i++) {
free(inspectionArray[i].dynamicString);
}
}
【问题讨论】:
-
"说话很便宜。给我看代码 - Linus"
-
没有动态数组。
-
我有很多代码,我不能全部放在这里。那我试试
-
你至少有两个完全独立的问题,一个是关于输出的,一个是关于内存管理的。在这里提出具体的问题,最好用代码来支持它们。
-
@LuisValdez 尝试创建minimal reproducible example
标签: c arrays string memory-management