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.
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()
andfree()
. 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: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
.