c - 动态分配变量名称

时间:2017-03-29 16:19:06

标签: c

我正在尝试从用户那里获取输入数量并接受输入然后将它们存储在动态创建的变量名称下。任何人都可以帮忙吗? 我想获取数组用户想要输入的数量,然后创建保持一个共同模式的确切数量的变量,这样我就可以知道哪个数组在哪个变量下,我可以调用它们进行进一步处理。

我目前的代码如下

 int input, eqn, m, i,n,x;  
    char inputarr[100], eqnarr[100];  
    printf("Enter number of variables: ");  
    scanf("%d",&n);  
    m=n;  
    printf("Enter your variables: \n");  
    while(n!=-1){  
    gets(inputarr[n]);  
    n--;  
    }  
    while(m!=0){  
    puts(inputarr[m]);  
    printf("\n");  
    m--;  
    }   

我的输入就像是 2(这里2是用户打算给出的输入数量)
a = 3
b = 4

我需要将它们保存在2个变量中,比如var1和var2,因为我需要稍后使用它们。

3 个答案:

答案 0 :(得分:0)

C不支持动态创建的变量。您可以通过调用malloc()来实例化动态对象,但这些对象不会被命名。在C中,名称只是用于在编译时将名称与内存位置相关联的标签,并在链接时解析。这在运行时太迟了。

您可以创建从名称到int值的映射,但不能创建新变量。映射将适合您。您需要创建一个方法来为映射添加命名值,一个检索值的方法,一个更新其值的方法,并且为了完整性,您需要第四种方法来删除不再需要它的元素。 / p>

以下是使用动态查找表将变量名称映射到int值的简单示例。要完成,您需要添加更新值的方法,并删除它们等等。

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

#define MAX_VARIABLES 100

typedef struct Lookup_Entry_Struct {
           char* Name;
           int   Value;
        } LookUp_Entry;

typedef struct Mapping_Struct {
           int   MaxEntries;
           int   NumEntries;
           LookUp_Entry* mapping;
        } Mapping;

void initMapping(Mapping* map, int MaxEntries)
{
 map->NumEntries = 0;
 map->MaxEntries = MaxEntries;
 map->mapping = calloc(sizeof(LookUp_Entry), MaxEntries);

 if (map->mapping == NULL) {
    // Failed to allocate the Mapping table
    fprintf(stderr, "Failed to alloc Mapping table of %d entries\n", MaxEntries);
    map->MaxEntries = 0;
 }
}


bool addMap(Mapping* map, char* Name, int Val)
{
 bool Added = false;

 if (map->NumEntries < map->MaxEntries) {
    // There is still room in the table, add this new variable
    LookUp_Entry* newEntry = &(map->mapping[map->NumEntries]);
    newEntry->Value = Val;
    newEntry->Name  = malloc(strlen(Name)+1);
    strcpy(newEntry->Name, Name);
    map->NumEntries++;
    Added = true;
 }

 return Added;
}


int lookup(Mapping* map, char* Name)
{
 int  val   = -1;
 int  i     = 0;
 bool Found = false;


 // Search the map to see if we can find Name
 for(i=0; i < map->NumEntries && !Found; i++)
   {
    LookUp_Entry* entry = &(map->mapping[i]);
    if (strcmp(entry->Name, Name) == 0) {
       // Found a match, return the value in *Val
       val   = entry->Value;
       Found = true;
    }
   }

 if (!Found)
    fprintf(stderr, "lookup of \"%s\" not found in map\n", Name);

 // Found value, or -1 if not found
 return val;
}

void getVariablesFromUser(Mapping* map)
{
 #define MAXNAMELEN  100
 // Code modified from Buno's sample
 int  NumVariables = 0;
 int  i;

 char inputName[100];
 int  inputVal;

 while ((NumVariables<1) || (NumVariables > MAX_VARIABLES)) {
    printf("Enter number of variables: ");
    scanf("%d", &NumVariables);
    if (NumVariables<0 || NumVariables>MAX_VARIABLES)
       fprintf(stderr, "Please enter no more than %d variables!\n", MAX_VARIABLES);
 }

 printf("Init mapping for %d variables\n", NumVariables);
 initMapping(map, NumVariables);

 for(i=0; i<NumVariables; i++) {
    printf("Enter variable #%d name and initial value: ", i+1);
    scanf("%s %d", &(inputName[0]), &inputVal);
    printf("Adding variable %s with initial value %d\n", inputName, inputVal);
    addMap(map, inputName, inputVal);

 }
}

int main(int argc, char** argv)
{
 Mapping myVarMap;
 char*   varName;
 int     i;

 getVariablesFromUser(&myVarMap);

 // Display all the variables to show how to retrieve values
 printf("%d variables added by user\n", myVarMap.NumEntries);
 for(i=0; i<myVarMap.NumEntries; i++) {
    LookUp_Entry *entry =  &(myVarMap.mapping[i]);
    char*         name  = entry->Name;
    printf("Entry #%d: %s = %d\n", i+1, name, lookup(&myVarMap,name));
 }
}

将其保存在文件lookup.c中,然后编译它:

gcc lookup.c -o lookup

以下是样本运行:

scott> lookup
Enter number of variables: 3
Init mapping for 3 variables
Enter variable #1 name and initial value: Bob 123
Adding variable Bob with initial value 123
Enter variable #2 name and initial value: Ted 999
Adding variable Ted with initial value 999
Enter variable #3 name and initial value: Sally 0
Adding variable Sally with initial value 0
3 variables added by user
Entry #1: Bob = 123
Entry #2: Ted = 999
Entry #3: Sally = 0
scott> 

答案 1 :(得分:0)

您无法动态创建变量名称,但是您可以使用名为&#39; malloc()&#39;的函数动态分配内存。您需要先了解指针,然后了解如何在运行时创建和访问内存。

答案 2 :(得分:0)

如其他人的评论和答案中所述,您无法在C中动态创建变量。

但是,您可以采用以下方法:

  • 动态读取n个表达式的每一行的字符(当 输入字符串的长度不固定)例如,考虑n = 1和 输入行是&#34; a = 10&#34;阅读每个角色&#39; a&#39;,&#39; =&#39; ,&#39; 1&#39; ,&#39; 0&#39;
  • 解析字符串&#34; a = 10&#34;获取值10.动态分配 用于存储此值的内存10.
  • 对所有n条输入行执行此操作。

以下是实现此目的的代码:

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

// Dynamically read the input string character by character: Taken from a SO answer
char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(char)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(char)*len);
}

int main(void) {
    int n,i,numindex;
    char *variableline,*vartemp;
    char keys[] = "1234567890";

    //Read in the number of variables
    printf("Enter n\n");
    scanf("%d\n",&n);

    printf("Enter %d lines\n",n);
    //Allocate memory for these variables
    int *variable_values = malloc(n*sizeof(int));
    for(i=0;i<n;i++){
        // Read the characters dynamically from the n input lines
        variableline = inputString(stdin, 10);

        //numindex - index where the number starts. For ex, in the string "a=12", numindex is the position of '1'
        numindex = strcspn (variableline,keys);

        //Read the number into vartemp
        vartemp = malloc(strlen(variableline));
        strncpy(vartemp, variableline+numindex, strlen(variableline) - numindex);

        //Convert the string to number
        *(variable_values+i) = atoi(vartemp);
    }

    printf("The variable values are:\n");
    // All the variable values are stored in the dynamically created memory variable_values
    for(i=0;i<n;i++)
    printf("%d\n",variable_values[i]);
    return 0;
}