如何使用结构指针访问结构内部的数组

时间:2011-12-29 17:46:03

标签: c pointers structure

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

如何使用struct指针访问struct中的数组?这是正确的方法吗?我在编译期间收到以下错误:

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

2 个答案:

答案 0 :(得分:4)

无法在C中复制数组。

您正在正确访问它们,但您需要按值复制数组值。

更改

p->a=b;

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

答案 1 :(得分:4)

p->a=b处的代码根本不允许作为数组而不是指针而您正在尝试将指针复制到数组。试试strncpy(p->a, b, 100)(当然你应该有100 #define

相关问题