質問

I have created a struct with a char variable in it. 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. try new_node->val instead of new_node.val

response to edited question As you have changed from char val to char *val you will need additional processing:

  1. allocate memory for *val : new_node->val=(char*)malloc(sizeof(char))
  2. assignment will need to dereference the pointer : *(new_node->val)="a"
  3. Print statement should also dereference the pointer : printf("%c",*(new_node->val))
  4. you should free the val pointer before freeing new_node: free(new_node->val)

他のヒント

new_node.val should be replaced with new_node->val. since new_node is a pointer. Keep in mind that new_node->val (often refereed as the arrow operator) is the shorthand for (*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. Use -Wall or other warning flags when you compilate your program to experience less logical errors or seg faults.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top