用C初始化字符串数组动态 [英] Initializing an array of strings dynamically in C

查看:179
本文介绍了用C初始化字符串数组动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以初始化字符串数组是这样的:

 静态为const char * BIN_ELEMENTS [5] = {
    0000 \\ 0,// 0
    0001 \\ 0,// 1
    0010 \\ 0,// 2
    0011 \\ 0,// 3
    0100 \\ 0,// 4
};

但我需要完成,在一个动态的方式。从文件中读取字符,并将它们插入到一个数组。然后,该数组复制到字符串(如上面)的数组。

因此​​,让我们说,我捕捉到从文件下列字符,并插入他们到一个数组,像这样的:

 字符数[5];
字符* listOfNumbers [10];
数[0] ='1';
号[1] ='2';
号码[2] ='3';
数[3] ='4';
数[4] ='\\ 0';

现在我想数的全部内容复制,到 listOfNumers [0] //这意味着我已经存储的1234在listOfNumers的0位置。 9留下更多的位置来存储不同的号码。

所以,我会做这样的事情:

  listOfNumers [0] =数字; //这实际上似乎工作。

不过,由于数字的一个巨大的文件,我需要重新使用该序列号,提取一个新号码。但是,当我做到这一点,pviously存储在listOfNumers内容$ P $ [0]被覆盖,eventho我更新了新号码的新位置。我该如何处理呢?

下面是我到目前为止有:

 字符数[5]; //用于存储阵列的数量
INT J = 0; //计数器
INT℃; //用于从文件中读取字符。
INT K = 0; //第二计数器
字符* listOfNumbers [10]; //阵列所有提取的数字。
FILE * INFILE;INFILE = FOPEN(prueba.txt,R);如果(INFILE){
    而((C = GETC(INFILE))!= EOF){
        如果(C ='!'和;&安培;!C ='\\ n')
            数[k]的= C;
            ++ K表;
        } //内结束,如果
        其他{
            数[K] ='\\ 0';
            listOfNumbers [J] =号;
            的printf(元素%d为:%S \\ n,J,listOfNumbers [J]); //输出正确的值
            ++焦耳;
            K = 0;
        } //其他结束    } //结束时
    FCLOSE(INFILE);
} //结束外,如果的printf(\\ nElement 0:%S \\ n,l​​istOfNumbers [0]); //失败 - 不正确的值
的printf(元素1:%S \\ n,l​​istOfNumbers [1]); //失败 - 不正确的值
的printf(元素2:%S \\ n,l​​istOfNumbers [2]);


解决方案

的char * listOfNumbers [10];只保留内存10指针为char。
和listOfNumbers [J] =号只存储在数组编号的地址。它不会复制序列号的内容。随着数addrs的从未因此改变每一个清单点的10个元素的相同的空间。

您需要使用malloc每个listOfNumber的预留空间的10元。你需要使用的strcpy到号码的内容复制到当前listOfNumber [K]

  listOfNumber [K] =的malloc(strlen的(数)+1); // LEN的预留空间
的strcpy(listOfNumbers [K]号)//复制串

不要忘了在年底释放listOfNumbers的每个元素...
同时也照顾到的事实,您的文件可能包含超过10串...

I know I can initialize an array of strings this way:

static const char *BIN_ELEMENTS[5] = {
    "0000\0",           // 0
    "0001\0",           // 1
    "0010\0",           // 2
    "0011\0",           // 3
    "0100\0",           // 4
};

But I need to accomplish that in a dynamic way. Reading the characters from a File, and inserting them into an array. Then copy that array into an array of strings (like above).

So let's say I captured the following chars from a File, and inserted them into an array, like these:

char number[5];
char *listOfNumbers[10];
number[0]='1';
number[1]='2';
number[2]='3';
number[3]='4';
number[4]='\0';

Now I would like to copy the whole content of number, into listOfNumers[0] // meaning that I've stored "1234" in position 0 of listOfNumers. Leaving 9 more positions to store different numbers.

So I would do something like this:

listOfNumers[0] = number; //this actually seems to work.

But since its a huge file of numbers, I need to reuse the array number, to extract a new number. But when I do that, the content previously stored in listOfNumers[0] gets overwritten, eventho I updated the new position for the new number. How can I deal with that?

Here is what I have so far:

char number[5]; // array for storing number
int j=0;        // counter
int c;          // used to read char from file.
int k=0;        // 2nd counter
char*listOfNumbers[10]; // array with all the extracted numbers.
FILE *infile; 

infile = fopen("prueba.txt", "r");

if (infile) {
    while ((c = getc(infile)) != EOF) {
        if(c != ' ' && c != '\n') 
            number[k] = c;
            ++k;
        } // end inner if
        else {
            number[k] = '\0';
            listOfNumbers[j] = number;
            printf("Element %d is: %s\n", j, listOfNumbers[j]); // prints correct value
            ++j;
            k=0;
        } // end else

    } // end while
    fclose(infile);
} // end outer if

printf("\nElement 0 is: %s\n", listOfNumbers[0]);  // fails - incorrect value
printf("Element 1 is: %s\n", listOfNumbers[1]);    // fails - incorrect value
printf("Element 2 is: %s\n", listOfNumbers[2]);    

解决方案

char *listOfNumbers[10]; only reserves memory for 10 pointers to char. And listOfNumbers[j] = number only stores the address of the array number. It does not copy the content of the array number. As number addrs never changes therefore each of the 10 elements of the 'list' point to the same space.

You need to use malloc for each of your 10 element of listOfNumber to reserve space. you need to use strcpy to copy the content of number to the current listOfNumber[k].

listOfNumber[k] = malloc(strlen(number)+1);  // reserve space of len 
strcpy(listOfNumbers[k],number) // copy string 

Do not forget to free each element of listOfNumbers at end... And also take care to the fact that your file may contain more than 10 strings ...

这篇关于用C初始化字符串数组动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆