Declaring arraz with dynamic content

2019-09-20 07:58发布

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条回答
forever°为你锁心
2楼-- · 2019-09-20 08:45

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 , 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.

查看更多
登录 后发表回答