【问题标题】:how to access an array inside structure using a structure pointer如何使用结构指针访问结构内部的数组
【发布时间】:2012-01-30 01:47:33
【问题描述】:
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;                                       
}

如何使用结构指针访问结构内的数组?这是正确的方法吗?我在编译过程中收到以下错误:

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

【问题讨论】:

    标签: c pointers structure


    【解决方案1】:

    您在p->a=b 的代码根本不允许,因为 a 是一个数组而不是一个指针,并且您正试图将一个指针复制到一个数组。试试strncpy(p->a, b, 100)(当然#define应该是100)

    【讨论】:

    • 其实我错了,我的建议还是正确的,但是原因不对,我更正了我的答案。我推荐使用 strncpy 而不是 for 循环,因为你想在其中放入一个字符串。
    【解决方案2】:

    数组不能在 C 中复制。

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

    改变

    p->a=b;
    

    进入

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

    【讨论】:

    • +1 因为您的示例具有说明性,尽管不是最有效的方法(可读性)。
    猜你喜欢
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    相关资源
    最近更新 更多