简体   繁体   中英

how to access an array inside structure using a structure pointer

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 *' "

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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