简体   繁体   English

将变量赋给struct成员

[英]Assign variable to struct member

I have created a struct with a char variable in it. 我已经创建了一个带有char变量的结构。 I want to assign a string value to it when using it inside of a method and then print it. 我想在方法中使用它时为其分配一个字符串值,然后打印它。 I have been looking around but can't find a valid answer, but can't find what I'm doing wrong. 我一直在环顾四周,但找不到有效的答案,但找不到我做错了什么。 Why am I getting the error below? 为什么我会收到以下错误?

Here is what I have tried: 这是我尝试过的:

struct node{
    char *val;
    struct node *first;
    struct node *last;
};


void main(){
      struct node *new_node;
new_node =(struct node *)malloc(sizeof(struct node));
   new_node.val = "a";
   printf("%s",new_node.val);
}

I get the error: 我收到错误:

request for member 'val' in something not a structure or union

new_node should be accessed as a pointer and not an instance. new_node应该作为指针而不是实例来访问。 try new_node->val instead of new_node.val 尝试new_node->val而不是new_node.val

response to edited question As you have changed from char val to char *val you will need additional processing: 对已编辑问题的响应当您从char val更改为char *val您将需要进行额外处理:

  1. allocate memory for *val : new_node->val=(char*)malloc(sizeof(char)) *val分配内存: new_node->val=(char*)malloc(sizeof(char))
  2. assignment will need to dereference the pointer : *(new_node->val)="a" 赋值将需要取消引用指针: *(new_node->val)="a"
  3. Print statement should also dereference the pointer : printf("%c",*(new_node->val)) Print语句也应该取消引用指针: printf("%c",*(new_node->val))
  4. you should free the val pointer before freeing new_node : free(new_node->val) 你应该在释放new_node之前释放val指针: free(new_node->val)

new_node.val should be replaced with new_node->val. new_node.val应替换为new_node-> val。 since new_node is a pointer. 因为new_node是一个指针。 Keep in mind that new_node->val (often refereed as the arrow operator) is the shorthand for (*new_node).val. 请记住,new_node-> val(经常被称为箭头运算符)是(* new_node).val的简写。

Also i believe you can write: 另外我相信你可以写:

node *new_node = malloc(sizeof(node));

For easier reading and cleaner code since malloc will just return a pointer to a given memory address. 为了更容易阅读和更清晰的代码,因为malloc只返回指向给定内存地址的指针。 Use -Wall or other warning flags when you compilate your program to experience less logical errors or seg faults. 在编译程序时使用-Wall或其他警告标志,以减少逻辑错误或seg故障。

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

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