结构指针未按预期保存字符数组

Struct pointer doesn't save character array as expected

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

结构没有按预期工作,给定的字符数组在检查时没有正确保存。

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

更好读

然后

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

也在 UPV 中?我认得这个 typedef,因为我也在为明天的作业而苦苦挣扎。我问了 Oscar,他告诉我你需要为 class 的构造函数中的结构分配内存 space。他甚至为我提供了一些示例代码,但我还没有成功。