简体   繁体   English

C 中的动态结构数组

[英]Dynamic Array of Structures in C

I'm trying to create an array of structures, but I'm not sure how to proceed with declaring an array and mallocing it.我正在尝试创建一个结构数组,但我不确定如何继续声明一个数组并对其进行分配。 Here is the code I have so far:这是我到目前为止的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAX_STRING 128

typedef char String[MAX_STRING]

typedef struct {
  String Name; //Name of the person                                             
  String Best; //Name of the best friend                                        
} Names;

int main(void) {

}

This is an exercise I'm trying to do and the end product should be like this:HERE这是我正在尝试做的一个练习,最终产品应该是这样的:这里

#include <stdlib.h>
#include <stdio.h>

#define N 3

typedef struct
{
    char* Name; //Why complicate things using a string?
    char* Best;
}Names;

int main(void)
{
    int i;
    //Create an array of pointers. 
    //Each element of the array is a pointer to a struct "Names"
    Names** data = malloc(N*sizeof(Names*));
    //data[i] is a array element which points to a single struct "Names".
    //Dynamically allocate memory for each struct
    for(i=0;i<N;i++)
    {
        data[i] = malloc(sizeof(Names));
    }
    //Rest is your assignment
    data[0]->Name = "aaaa";
    data[0]->Best = "bbbb";
    data[1]->Name = "cccc";
    data[1]->Best = "dddd";
    data[2]->Name = "eeee";
    data[2]->Best = "ffff";
    for(i=0;i<N;i++)
    {
        printf("%s\t%s\n",data[i]->Name,data[i]->Best);
    }
}
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MAX_STRING 128
#define NUMBER_OF_STRUCTURES_IN_ARRAY 10

typedef char String[MAX_STRING]

typedef struct {
  String Name; //Name of the person                                             
  String Best; //Name of the best friend                                        
} Names;

int main(void) 
    {
    int rCode=0;
    Names *names_A = NULL;
    int    index;

    names_A = malloc(sizeof(*names_A) * NUMBER_OF_STRUCTURES_IN_ARRAY);
    if(NULL == names)
        {
        rCode=ENOMEM;
        fprintf(stderr, "Error: malloc() failed\n");
        goto CLEANUP;
        }

     for(index=0; index < NUMBER_OF_STRUCTURES_IN_ARRAY; ++index)
         {
         strcpy(names_A[index].Name, "Some Name");
         strcpy(names_A[index].Best, "Another Name");
         }

CLEANUP:

if(names_A)
   free(names_A);

return(rCode);
}

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

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