Declaring arraz with dynamic content

别来无恙 提交于 2020-01-07 08:13:08

问题


Hello I want to make program wich will say how many big and short letters is in the word and such but run in to the problem I can't declare content of array dynamically. This is all C code. I tried this

char something;
scanf("%c",somethnig);
char somethingmore[]=something;
printf("%c",something[0])

but it wasn't possible to compile I also tried something like this

char *something;
scanf("%c",something);
printf("%c",something[0]);

wich was possible to compile but crushed when called array pointer(I apoligize if the naming is wrong) I programing beginner so this is maybe silly question. This is all just example of problem I run to not code of my program.


回答1:


Well, disregarding the weirdly wrong syntax in your snippet, I think a good answer comes down to remind you of one thing:

C doesn't do any memory management for you.

Or, in other words, managing memory has to be done explicitly. As a consequence, arrays have a fixed size in C (must be known at compile time, so the compiler can reserve appropriate space in the binary, typically in a data segment, or on the stack for a local variable).

One notable exception is variable length arrays in c99, but even with them, the size of the array can be set only one time -- at initialization. It's a matter of taste whether to consider this a great thing or just a misfeature, but it will not solve your problem of changing the size of something at runtime.

If you want to dynamically grow something, there's only one option: make it an allocated object and manage memory for it yourself, using the functions malloc(), calloc(), realloc() and free(). All these functions are part of standard C, so you should read up on them. A typical usage (not related to your question) would be something like:

#include <stdlib.h>

int *list = 0;
size_t capacity = 0;
size_t count = 0;

void append(int value)
{
    if (capacity)
    {
        if (count == capacity)
        {
            /* reserve more space, for real world code check realloc()
             * return value */
            capacity *= 2;
            list = realloc(list, capacity * sizeof(int));
        }
    }
    else
    {
        /* reserve an initial amount, for real world code check malloc()
         * return value */
        capacity = 16;
        list = malloc(capacity * sizeof(int));
    }

    list[count++] = value;
}

This is very simplified, you'd probably define a container as a struct containing your pointer to the "array" as well as the capacity and count members and define functions working on that struct in some real world code. Or you could go and use predefined containers in a library like e.g. glib.



来源:https://stackoverflow.com/questions/33455240/declaring-arraz-with-dynamic-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!