繁体   English   中英

初始化struct指针

[英]initialize the struct pointer

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

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

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

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

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

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

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

您可以使用此动态分配C结构吗?

这是一个重复的问题。

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

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

在这里你可以理解它是如何工作的:

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

注意: - 如果你有结构使用的变量. 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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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