3
struct node{
    char a[100];
    struct node* next;
};
typedef struct node* nodeptr;
main()
{
    char b[100];
    nodeptr p;  
    int n;          
    printf("enter the string\n");
    scanf("%s",b);          
    n=strlen(b);                
    p=getnode();                    
    p->a=b;                             
    p->next=null;                           
    printf("%s \n",(q->a));                     
    return 0;                                       
}

How can I access the array inside the struct using a struct pointer? Is this the correct method? I am getting the following error during compilation:

incompatible types when assigning to type ‘char[100]’ from type ‘char *’ "

2 Answers 2

4

Your code at p->a=b is simply not allowed as a is an array and not a pointer and you are trying to copy a pointer to an array. Try strncpy(p->a, b, 100) (of course you should have 100 as a #define)

Sign up to request clarification or add additional context in comments.

1 Comment

Actually I was wrong, my suggestion is still correct, but the reason is wrong, I corrected my answer. And I recommend strncpy instead of a for loop because you want to put a string into it.
4

Arrays can not be copied in C.

You are accessing them correctly but you need to copy the array value by value.

Change

p->a=b;

Into

for(int loop=0;loop < 100;++loop)
{
    p->a[loop] = b[loop];
}

1 Comment

+1 because your example is illustrative, despite not the most efficient way (readability-wise) to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.