Home > Blockchain >  Struct pointer doesn't save character array as expected (Solved)
Struct pointer doesn't save character array as expected (Solved)

Time:10-28

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;
}
  • Related