初始化struct指针

时间:2013-08-05 09:02:59

标签: c struct initialization

typedef struct
{
  char *s;
  char d;
}EXE;
EXE  *p;

对于上面的struct,如何使用指针初始化结构?我知道对于非指针我们做EXE a[] = { {"abc",1}, {"def",2} };。同样在分配内存后是否可以使用指针?比如说p[] = { {"abc",1},.. so on}。基本上我想动态初始化。感谢。

3 个答案:

答案 0 :(得分:7)

我们可以使用指针初始化结构,如下所示

example:
 int i;
 char e[5]="abcd";
 EXE *p=malloc(sizeof(*p));
 for(i = 0;i < 5;i++)
   *(p+i)=(EXE){e,i+48};

答案 1 :(得分:1)

首先,您需要为char *分配一些内存,然后使用strcpy库函数来复制结构元素的数据。

p->s = strcpy(s,str);  //where str source, from where you need to copy the data

我希望这会有所帮助。虽然我可以为你提供完整的代码,但我希望你试试。

你可以用它 Dynamically allocate C struct?

这是一个重复的问题。

答案 2 :(得分:1)

您必须了解分配指针的工作原理:

  1. 假设您为三个结构Ptr = malloc(3*sizeof(EXE))分配了内存。
  2. 然后当你向Ptr添加1时,它会进入下一个结构。你有一块内存除以3(每个结构有3个较小的内存块)。
  3. 因此,需要访问第一个结构的元素,然后将指针移动到下一个结构。
  4. 在这里你可以理解它的工作原理:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct {
        char *s;
        char d;
    } EXE;
    
    int main()
    {
        int i;
        EXE *Ptr;
    
        Ptr = malloc(3*sizeof(EXE)); // dymnamically allocating the
                                     // memory for three structures
        Ptr->s = "ABC";
        Ptr->d = 'a';
    
    //2nd
        Ptr++;     // moving to the 2nd structure
        Ptr->s = "DEF";
        Ptr->d = 'd';
    
    //3rd
        Ptr++;    // moving to the 3rd structure
        Ptr->s = "XYZ";
        Ptr->d = 'x';
    
    //reset the pointer `Ptr`
        Ptr -= 2; // going to the 1st structure
    
    //printing the 1st, the 2nd and the 3rd structs
        for (i = 0; i < 3; i++) {
            printf("%s\n", Ptr->s);
            printf("%c\n\n", Ptr->d);
            Ptr++;
        }   
    
        return 0;
    }
    

    <强>注意:   - 如果你有一个struct的变量,可以使用. opereator来访问这些元素。   - 如果您有一个指向结构的指针,请使用->运算符来访问元素。

         #include <stdio.h>
         #include <stdlib.h>
    
         struct EXE {
             int a;
         };
    
         int main(){
    
        struct EXE variable;
        struct EXE *pointer;
    
        pointer = malloc(sizeof(struct EXE)); // allocating mamory dynamically 
                                          // and making pointer to point to this
                                          // dynamically allocated block of memory
        // like here
        variable.a = 100;
        pointer->a = 100;
    
        printf("%d\n%d\n", variable.a, pointer->a);
    
        return 0;
        }