首页 > 解决方案 > 结构指针未按预期保存字符数组

问题描述

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

该结构根本无法按预期工作,给定的 char 数组在检查时未正确保存。

标签: cpointersstruct

解决方案


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

推荐阅读