创建一个由const char指针指向的动态字符串数组

时间:2010-12-22 07:54:04

标签: c string pointers

我想在C中创建一个动态增长并存储字符串的数组。并希望通过指针指向该数组。我该怎么做?任何建议都将受到高度赞赏。我想制作的节目流程如下:

program takes input say int i =5;
create an string array of length 5
insert the string into the array.
suppose x1,x2,x3,x4,x5
and i want that array to be pointed by the const char pointer 

[编辑]

在这里,我想让我的问题更清楚。我将输入作为一些我必须存储的符号。如果我将输入作为5,那么我的程序必须生成五个符号,它必须存储到数组中,然后该指针指向该数组。

我的接近方式是:

我正在接受一系列指针。每个指针都指向带有两个元素的字符串。第一个元素对所有人来说都是一样的。每次迭代中的下一个元素必须增加1并且必须以输入i结束,我之前已经采用了。我的问题是将计数器值存储为字符。

我不习惯C.希望得到一些帮助。

谢谢

2 个答案:

答案 0 :(得分:1)

想法是使用malloc。假设这是你的const char指针:

const char *string;

现在您可以使用malloc分配尽可能多的空间:

string = malloc(number_of_chars_in_the_string);
// don't forget to test that string != NULL

如果结果太小,可以使用以下方法调整大小:

string = realloc(string, new_size);

当你完成它之后,你释放了记忆:

free(string);

答案 1 :(得分:1)

以下是一个例子:

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

int main()
{
    int numElem = 0;

    scanf("%d", &numElem);

    printf("numElem: %d", numElem);

    char *string = (char *) malloc( (numElem * sizeof(char)));
    //checking of NULL here in case malloc fails
    //...

    //enter you chars here...
    //etc...

    return 0;
}

此代码段的主要思想是使用:char *string = (char *) malloc( (numElem * sizeof(char)));使其动态化 希望这会有所帮助。