English 中文(简体)
如何动态地分配记忆空间,以加以扼杀,并从用户那里获得这种空间?
原标题:How to dynamically allocate memory space for a string and get that string from user?

我想读一下使用C方案用户的投入。 我不想像现在这样使用阵列。

char names[50];

因为如果用户给出10年长的描述,则其余空间被压缩。

如果我这样使用特性点,

char *names;

然后,我需要以这种方式为之献计,

names = (char *)malloc(20 * sizeof(char));

在这种情况下,还有可能浪费记忆。

因此,我所需要的是,将记忆注入一个与扼杀时间完全相同的扼杀。

让我们承担,

如果用户投入为stackoverflow",那么所分配的记忆应为14(即,舱位的长度=13和 space的新增空间)。

我如何能够做到这一点?

最佳回答

在时间(使用getc(stdin))上读一个特性,并在你行时增加(realloc)。

我在一段时间前曾写过这一职能。 说明仅供参考。

char *getln()
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch) {
        ch = getc(stdin);

        /* Check if we need to stop. */
        if (ch == EOF || ch ==  
 )
            ch = 0;

        /* Check if we need to expand. */
        if (size <= index) {
            size += CHUNK;
            tmp = realloc(line, size);
            if (!tmp) {
                free(line);
                line = NULL;
                break;
            }
            line = tmp;
        }

        /* Actually store the thing. */
        line[index++] = ch;
    }

    return line;
}
问题回答

你可以有一个阵列,从10个部分开始。 阅读材料的性质。 如果接下去,再再再再花5个。 不是最好的,但你可以稍后腾出其他空间。

如果你要不忘记忆,每时就用果子和真菌读。 业绩将死去,但你会把这10个 by子 spare。

另一项好的权衡是,在一份功能(使用当地变量)中阅读,然后复制。 因此,大缓冲将发挥范围的作用。

你们也可以使用定期表达方式,例如:

char *names
scanf("%m[^
]", &names)

整个线将从平线上走,积极分配所需的空间。 当然,在此之后,你必须免费打<代码>。

下面是建立动态体的法典:

void main()
{
  char *str, c;
  int i = 0, j = 1;

  str = (char*)malloc(sizeof(char));

  printf("Enter String : ");

  while (c !=  
 ) {
    // read the input from keyboard standard input
    c = getc(stdin);

    // re-allocate (resize) memory for character read to be stored
    str = (char*)realloc(str, j * sizeof(char));

    // store read character by making pointer point to c
    str[i] = c;

    i++;
    j++;
  }

  str[i] =   ; // at the end append null character to mark end of string

  printf("
The entered string is : %s", str);

  free(str); // important step the pointer declared must be made free
}

第一,确定新的功能,读取投入(根据您的投入结构),并储存座标,这意味着使用的记忆。 限定时间足以供你参考。

其次,使用<代码>strlen/code>来衡量以前储存的座右铭的确切使用长度,并 小型 用于在座标中分配记忆,其长度由<代码>strlen界定。 守则如下。

int strLength = strlen(strInStack);
if (strLength == 0) {
    printf(""strInStack" is empty.
");
}
else {
    char *strInHeap = (char *)malloc((strLength+1) * sizeof(char));
    strcpy(strInHeap, strInStack);
}
return strInHeap;

最后,将<代码>strInStack至strInHeap的数值改为strcpy,并将点名改为strIn Heap。 <>Stack将自动免费,因为它只在这一次功能中退出。

这是一项功能幻灯片,我写道,扫描用户对插座的投入,然后储存与用户投入相同的大小。 请注意,我最初将 j的数值降至2,以便能够储存的特性。

char* dynamicstring() {
    char *str = NULL;
    int i = 0, j = 2, c;
    str = (char*)malloc(sizeof(char));
    //error checking
    if (str == NULL) {
        printf("Error allocating memory
");
        exit(EXIT_FAILURE);
    }

    while((c = getc(stdin)) && c !=  
 )
    {
        str[i] = c;
        str = realloc(str,j*sizeof(char));
        //error checking
        if (str == NULL) {
            printf("Error allocating memory
");
            free(str);
            exit(EXIT_FAILURE);
        }

        i++;
        j++;
    }
    str[i] =   ;
    return str;
}

在主(主)项中,你可以宣布另一个可变的果园,以储存有活力的胎体的回报价值,然后在你重新使用时免除这一果园。

char* load_string()
 {

char* string = (char*) malloc(sizeof(char));
*string =   ;

int key;
int sizer = 2;

char sup[2] = {  };

while( (key = getc(stdin)) !=  
 )
{
    string = realloc(string,sizer * sizeof(char));
    sup[0] = (char) key;
    strcat(string,sup);
    sizer++

}
return string;

}

int main()
  {
char* str;
str = load_string();

return 0;
  }

realloc is a pretty expensive action... here s my way of receiving a string, the realloc ratio is not 1:1 :

char* getAString()
{    
    //define two indexes, one for logical size, other for physical
    int logSize = 0, phySize = 1;  
    char *res, c;

    res = (char *)malloc(sizeof(char));

    //get a char from user, first time outside the loop
    c = getchar();

    //define the condition to stop receiving data
    while(c !=  
 )
    {
        if(logSize == phySize)
        {
            phySize *= 2;
            res = (char *)realloc(res, sizeof(char) * phySize);
        }
        res[logSize++] = c;
        c = getchar();
    }
    //here we diminish string to actual logical size, plus one for 
    res = (char *)realloc(res, sizeof(char *) * (logSize + 1));
    res[logSize] =   ;
    return res;
}




相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签