1
My goal is to allocate memory "down", making a genre of an array, in which the string length is static Maxlength and the number of strings that is placed is used dynamic memory.
#define MaxLength 35
typedef struct{
char RoomName[MaxLength];
char *SensorName[MaxLength];
unsigned int SensorCount;
char *Actuador[MaxLength];
unsigned int ActuadorCount;
}DataStruct;
void ToSensorName(DataStruct *Data, char *token){
Data->SensorCount++;
printf("Count inicial: %d", Data->SensorCount);
Data->SensorName[MaxLength]= realloc(Data->SensorName[MaxLength], Data->SensorCount * sizeof(char*));
strcpy(Data->SensorName[Data->SensorCount-1], token);
printf("\n\nFuncao: %s count: %d\n\n",Data->SensorName[Data->SensorCount-1], Data->SensorCount);
}
void ToStruct(DataStruct *Data, char *token, short *count){
switch(*count){
case 0:
strcpy(Data->RoomName, token);
printf("\n->%s<-", Data->RoomName);
break;
case 1:
ToSensorName(Data, token);
break;
case 2:
*count= -1;
break;
default:
printf("Error count");
break;
}
(*count)++;
}
Problem:
- In function Tosensorname The value of Sensorcount decreases
- In main when I call again print as null, that is, I am not putting the value by reference.
int main()
{
DataStruct Data;
Data.SensorCount=0;
Data.ActuadorCount=0;
const char *filename="SensorConfigurations.txt";
char buff[MaxBuffer];
FILE *SensorConviguration;
SensorConviguration=fopen(filename, "r");
if(SensorConviguration==NULL)
{
printf("Could not open file %s",filename );
return 1;
}
char *token;
short count=0;
while(fgets(buff, MaxBuffer, SensorConviguration)!= NULL)
{
//printf("%s\n", buff);
system("PAUSE");
/* get the first token */
token = strtok(buff, ":");
/*POSSIVEL PROBLEMA*/
ToStruct(&Data, token, &count);
/* walk through other tokens */
while( token != NULL )
{
printf( "%s\n", token );
token = strtok(NULL, ":");
}
}
/*POSSIVEL PROBLEMA*/
printf("\n\n\nMain: %s", Data.SensorName[0]);
fclose(SensorConviguration);
return 0;
}
Note: I have tried to find a similar question that would help me here, but I end up not being able to solve the problem.