简体   繁体   English

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

[英]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;
}

The struct simply doesn't work as expected, the char array given is not saved properly when checked.该结构根本无法按预期工作,检查时未正确保存给定的 char 数组。

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

Also in the UPV?也在UPV? I recognize this typedef because I am also struggling with tomorrow's assignment.我认识这个 typedef,因为我也在为明天的任务而苦苦挣扎。 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.他甚至为我提供了一些示例代码,但我还没有设法使它工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM