Home > database >  Struct pointer doesn't save character array as expected
Struct pointer doesn't save character array as expected

Time:10-29

typedef struct _Text { 
  char *str; 
  int length; 
  int counter; 
  } *Text;


int main(void) {
  Text txt= malloc(sizeof(Text));
  char *txtStr="hi";
  txt->str=txtStr;
  return 0;
}

The struct simply doesn't work as expected, the char array given is not saved properly when checked.

CodePudding user response:

typedef struct Text { 
  char *str; 
  int length; 
  int counter; 
  } Text;

is better to read

and then

int main(void) {
  Text *txt = malloc( sizeof( Text ));
  
  txt->str = malloc( sizeof( char ) *3);
  strcpy( txt->str, "hi" );

  printf("%s\n", txt->str );
  
  return 0;
}

CodePudding user response:

Also in the UPV? I recognize this typedef because I am also struggling with tomorrow's assignment. I asked Oscar and he told me that you need to memory allocate space for the structure within the constructor of the class. He even provide me with some example code, yet I haven't managed to make it work yet.

  • Related