有4个.c / .h文件。每个都有一些全局变量&结构变量。我从.map文件中获取了所有变量名称。我在二维数组/ * array [](char类型)中提取了所有内容。现在我想传递每个变量和地址的sizeof
答案 0 :(得分:0)
确定。如果需要在变量中分配动态内存,则需要在“stdlib.h”中使用malloc函数并读取该文件,您可以将其存储到链表中以逐个处理。
检查示例...... 我们在这个语义中有一个'variables.map':
eua 40
brasil 30
paris 15
horse 8
第一列是变量的名称(最多40个字符参见struct prototype ),第二列是大小。 (注意:由换行'\ n'分开)
程序将文件加载到内存中的链表中并分配相应的内存空间(检查main())。
参见示例程序......
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//MAP prototype
typedef struct map {
char name[40];
unsigned int size;
struct map *next;
} map;
//---
//Prototypes
void createList();
void insert(char[], int, map*);
void showList(map*);
unsigned int searchVariable(char[], map*);
void parseMapFile(char[]);
//---
//List, Linked list pointer
map *list_variables;
//---
//Main!
int main(int argc, const char * argv[])
{
//Create list!
createList();
//Parse the .Map file into struct
parseMapFile("/Users/gabriel/Documents/variables.map");
//Show linked list
//showList(list_variables);
//------
//Lets go now allocate the variables with the size in .map file
//Allocate space!
//Tipical types
int *eua = malloc(searchVariable("eua", list_variables) * sizeof(int));
char *brasil = malloc(searchVariable("brasil", list_variables) * sizeof(char));
float *paris = malloc(searchVariable("paris", list_variables) * sizeof(float));
//Alloc the void type (Undefined)
void *horse = malloc(searchVariable("horse", list_variables) * sizeof(void));
//---
//Set values
*eua = 5; //Integer
strcpy(brasil, "Cool!"); //String
*paris = 3.14; //Float
*(int*)horse = (int) 7; //Set a integer value to void pointer!
//---
//Show up!
printf("Variable eua: %d \n", *eua);
printf("Variable brasil: %s \n", brasil);
printf("Variable paris: %f \n", *paris);
printf("Variable horse: %d \n", *((int*)horse));
return EXIT_SUCCESS;
}
//Linked list functions...
//Allocate the linked list on memory
void createList() {
list_variables = malloc( sizeof (map));
list_variables->next = NULL;
}
//Insert the .MAP values into linked list
void insert(char name[], int size, map *p)
{
map *new;
new = malloc( sizeof (map));
new->size = size;
strcpy(new->name, name);
new->next = p->next;
p->next = new;
}
//Show variables loaded from .MAP file
void showList(map *list)
{
map *p;
for (p = list->next; p != NULL; p = p->next)
printf("Variable: %s, Size: %d \n", p->name, p->size);
}
//Search variable in memory and return the size respective
unsigned int searchVariable(char name[], map *list)
{
map *p;
p = list->next;
while (p != NULL && strcmp(name, p->name) != 0)
p = p->next;
return p->size;
}
//---
//Procedure to parse the map file in the specified structure!
void parseMapFile(char path[]) {
char line[80];
char name[40];
unsigned int size;
FILE *fp = fopen(path, "r");
while(fgets(line, 80, fp) != NULL)
{
sscanf (line, "%s %d", name, &size);
insert(name, size, list_variables);
}
fclose(fp);
}
有了这个,你真的可以用存储在文件中的值来分配动态空间。