我正在尝试创建一个结构数组,但我不知道如何声明数组并对其进行mallocate
#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) {
}
这是我正在尝试做的一个练习,最终产品应该是这样的: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("%st%sn",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() failedn");
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);
}