You said: certain amount of numbers; do you know that number upfront? If yes - you can allocate memory for that many values. If not - you'd need to implement some logic to allocate additional storage as needed. For example by doubling the already allocated space. You can increment the capacity by one to avoid wasted space, at the cost of repeated copying of your data.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch = 0;
int size = 0, capacity = 1;
int* c = malloc(sizeof(int) * capacity);
while (1) {
scanf("%d%c", &c[size], &ch);
if (ch == '\n')
break;
size++;
if (size == capacity)
{
capacity *= 2; // use whatever policy to increase the capacity
c = realloc(c, sizeof(int) * capacity);
}
}
return 0;
}
Answer from Vlad Feinstein on Stack OverflowUser input and dynamic memory allocation in C - Stack Overflow
How to read input of a string with an indefinite size using Dynamic Memory Allocation?
c - How to dynamically allocate memory space for a string and get that string from user? - Stack Overflow
Dynamically Allocated Array of strings?
Im trying to create a program that takes a users commands and with them creates an HTML file.So for example the input could be newPar [text].And the command will be saved in a string called cmd that has a max of 10 characters.But how can I save the input that is the text of the paragraph in a string that I dont know the length of until the user has typed it?
Edit:Thank you all for the help!!Every suggestion was extremely helpful!Sorry for not answering to all of the comments and taking a while to answer or upvote the comments Unfortunately I didnt manage to finish the program before the deadline I needed to due to other problems I had with making it and not having enough time.But again thank you for helping me overcome the problem I very much appreciate it! :)
Read one character at a time (using getc(stdin)) and grow the string (realloc) as you go.
Here's a function I wrote some time ago. Note it's intended only for text input.
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 == '\n')
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;
}
You could have an array that starts out with 10 elements. Read input character by character. If it goes over, realloc another 5 more. Not the best, but then you can free the other space later.