I am trying to take number of inputs from a user and take the inputs then and store them under dynamically created variable names. can anyone help?
I want to take the number of array user want to input then create the exact number of variables which maintains a common pattern so I can know which array is under which variable and I can call them for further processing.
My current code is as follows
int input, eqn, m, i,n,x;
char inputarr[100], eqnarr[100];
printf("Enter number of variables: ");
scanf("%d",&n);
m=n;
printf("Enter your variables: \n");
while(n!=-1){
gets(inputarr[n]);
n--;
}
while(m!=0){
puts(inputarr[m]);
printf("\n");
m--;
}
my inputs are like
2 (here 2 is number of inputs user intended to give)
a = 3
b = 4
I need to save them in 2 variables say var1 and var2 as I need to work with them later.
C does not support dynamically created variables. You can instantiate dynamic objects through calls to malloc(), but these will not be named. In C, names are just labels used to associate names to memory locations at compile time, and resolved at link time. It is way too late at run time.
You can create a mapping from names to int values, but you cannot create new variables. A Mapping will work for you. You need to create a method to add a named value to your mapping, a method to retrieve the value, a method to update its value, and for completeness, you need a fourth method to delete an element when you no longer need it.
Here is a simple example of mapping variable names to int values using a dynamic lookup table. To be complete, you would need to add methods for updating values, and deleting them, etc.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_VARIABLES 100
typedef struct Lookup_Entry_Struct {
char* Name;
int Value;
} LookUp_Entry;
typedef struct Mapping_Struct {
int MaxEntries;
int NumEntries;
LookUp_Entry* mapping;
} Mapping;
void initMapping(Mapping* map, int MaxEntries)
{
map->NumEntries = 0;
map->MaxEntries = MaxEntries;
map->mapping = calloc(sizeof(LookUp_Entry), MaxEntries);
if (map->mapping == NULL) {
// Failed to allocate the Mapping table
fprintf(stderr, "Failed to alloc Mapping table of %d entries\n", MaxEntries);
map->MaxEntries = 0;
}
}
bool addMap(Mapping* map, char* Name, int Val)
{
bool Added = false;
if (map->NumEntries < map->MaxEntries) {
// There is still room in the table, add this new variable
LookUp_Entry* newEntry = &(map->mapping[map->NumEntries]);
newEntry->Value = Val;
newEntry->Name = malloc(strlen(Name)+1);
strcpy(newEntry->Name, Name);
map->NumEntries++;
Added = true;
}
return Added;
}
int lookup(Mapping* map, char* Name)
{
int val = -1;
int i = 0;
bool Found = false;
// Search the map to see if we can find Name
for(i=0; i < map->NumEntries && !Found; i++)
{
LookUp_Entry* entry = &(map->mapping[i]);
if (strcmp(entry->Name, Name) == 0) {
// Found a match, return the value in *Val
val = entry->Value;
Found = true;
}
}
if (!Found)
fprintf(stderr, "lookup of \"%s\" not found in map\n", Name);
// Found value, or -1 if not found
return val;
}
void getVariablesFromUser(Mapping* map)
{
#define MAXNAMELEN 100
// Code modified from Buno's sample
int NumVariables = 0;
int i;
char inputName[100];
int inputVal;
while ((NumVariables<1) || (NumVariables > MAX_VARIABLES)) {
printf("Enter number of variables: ");
scanf("%d", &NumVariables);
if (NumVariables<0 || NumVariables>MAX_VARIABLES)
fprintf(stderr, "Please enter no more than %d variables!\n", MAX_VARIABLES);
}
printf("Init mapping for %d variables\n", NumVariables);
initMapping(map, NumVariables);
for(i=0; i<NumVariables; i++) {
printf("Enter variable #%d name and initial value: ", i+1);
scanf("%s %d", &(inputName[0]), &inputVal);
printf("Adding variable %s with initial value %d\n", inputName, inputVal);
addMap(map, inputName, inputVal);
}
}
int main(int argc, char** argv)
{
Mapping myVarMap;
char* varName;
int i;
getVariablesFromUser(&myVarMap);
// Display all the variables to show how to retrieve values
printf("%d variables added by user\n", myVarMap.NumEntries);
for(i=0; i<myVarMap.NumEntries; i++) {
LookUp_Entry *entry = &(myVarMap.mapping[i]);
char* name = entry->Name;
printf("Entry #%d: %s = %d\n", i+1, name, lookup(&myVarMap,name));
}
}
Save this in file lookup.c, then to compile it:
gcc lookup.c -o lookup
Here is sample run:
scott> lookup
Enter number of variables: 3
Init mapping for 3 variables
Enter variable #1 name and initial value: Bob 123
Adding variable Bob with initial value 123
Enter variable #2 name and initial value: Ted 999
Adding variable Ted with initial value 999
Enter variable #3 name and initial value: Sally 0
Adding variable Sally with initial value 0
3 variables added by user
Entry #1: Bob = 123
Entry #2: Ted = 999
Entry #3: Sally = 0
scott>
You cannot create variable names dynamically, however you can dynamically allocate memory using a function called 'malloc()'. You need to first understand pointers and then learn how to create and access memory during run-time.
As mentioned in the comments and answers of others, you cannot dynamically create variables in C.
However, you can follow this approach:
Dynamically read the characters for each line of n expressions (When the
length of input string is not fixed) For ex, Consider n =1 and the
input line is "a=10" Read each character 'a', '=' , '1' , '0'
Parse the string "a=10" to obtain the value 10. Dynamically allocate
memory to store this value 10.
Do this for all n input lines.
Here is the code to achieve this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Dynamically read the input string character by character: Taken from a SO answer
char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
char *str;
int ch;
size_t len = 0;
str = realloc(NULL, sizeof(char)*size);//size is start size
if(!str)return str;
while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
str[len++]=ch;
if(len==size){
str = realloc(str, sizeof(char)*(size+=16));
if(!str)return str;
}
}
str[len++]='\0';
return realloc(str, sizeof(char)*len);
}
int main(void) {
int n,i,numindex;
char *variableline,*vartemp;
char keys[] = "1234567890";
//Read in the number of variables
printf("Enter n\n");
scanf("%d\n",&n);
printf("Enter %d lines\n",n);
//Allocate memory for these variables
int *variable_values = malloc(n*sizeof(int));
for(i=0;i<n;i++){
// Read the characters dynamically from the n input lines
variableline = inputString(stdin, 10);
//numindex - index where the number starts. For ex, in the string "a=12", numindex is the position of '1'
numindex = strcspn (variableline,keys);
//Read the number into vartemp
vartemp = malloc(strlen(variableline));
strncpy(vartemp, variableline+numindex, strlen(variableline) - numindex);
//Convert the string to number
*(variable_values+i) = atoi(vartemp);
}
printf("The variable values are:\n");
// All the variable values are stored in the dynamically created memory variable_values
for(i=0;i<n;i++)
printf("%d\n",variable_values[i]);
return 0;
}
Related
In my register, I want to find all the words that match user input and display them.
For example if I have words like redapple, rottenapple, apple, banana in my register.
And user inputs apple I want to be able to dispaly redapple, rottenapple, apple and their itemnumber and inventory balance. I cannot display in the right way and cannot figure it why, have tried different way and I will post my last try. Thank you!
void search(Car a[],int nr){
char ItmName[50];
int i;
while(1){
printf("Type item name (q for menu): ");
scanf("%s%*c", &ItmName);
if(strcmp(ItmName,"q")==0){
return;
}else{
for(i=0;i<nr;i++){
char *word = strstr(a[i].name,ItmName);
for(i=0;i<nr;i++)
if(word==itemN){
printf("%d\t\t%s\t\t%d\n", a[i].itemNmr, a[i].name, a[i].inventory);
}
return;
}
}
}
}
Your nested loop use the same control variable, i, and continuation condition, which ensures only one iteration of the outer loop occurs.
The contents of the loop make little sense. You repeatedly compare a pointer to the first element of the input buffer (itemN; pressumably itemName) against the pointer value returned by strstr, after it looks through the name field of only the first element of the a array for the substring provided in itemName.
Rewritten verbosely, this reads as
for (i = 0; i < nr; i++) {
for (i = 0; i < nr; i++) {
if (strstr(a[0].name, itemName) == &itemName[0]) {
printf(/* some information */);
}
}
}
which hopefully you can see makes no sense. A pointer value that points to an element of a[0].name will never be equal to the pointer value that points to the first element of itemName - as that would require their memory to overlap somehow.
In any case, this should not require any nested loops, as this can be done with a linear search of your array of structures.
First suggestion: move the user input to outside the function. Make search accept a third argument, a string to search for in each structures name. Separately (and repeatedly) take user input and then call this function.
Second suggestion: forget scanf exists entirely. Use fgets (and sscanf if you need to extract formatted data from the string).
Here's a cursory example of a linear search function:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[128];
unsigned inventory;
} Car;
void search(Car *cars, size_t length, const char *query)
{
for (size_t i = 0; i < length; i++)
if (strstr(cars[i].name, query))
printf("NAME: [%s]\tQUANT: [%u]\n", cars[i].name, cars[i].inventory);
}
int main(void)
{
Car cars[] = {
{ "redapple", 10 },
{ "rottenapple", 7 },
{ "foo", 4 },
{ "bar", 15 },
{ "candyapple", 11 }
};
size_t len = sizeof cars / sizeof *cars;
while (1) {
char buf[512];
printf("Enter a search string (. = exit): ");
fflush(stdout);
if (!fgets(buf, sizeof buf, stdin))
return 1;
if ('.' == *buf)
return 0;
/* remove any trailing CRLF */
buf[strcspn(buf, "\r\n")] = '\0';
search(cars, len, buf);
}
}
So I am pretty much trying to create an array that functions as following:
1)I enter a string (in a temporary array like char temp[...] for example)
2)I create a while loop that ends when the first character of temp is \x0
3)Inside the loop I use the malloc function to create space for each string
4)I print the strings
Problem is that whenever i try to run my program it crushes and the compiler isn't helping me much.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE 80
int main(){
char **pin;
char temp[LINE];
int index = 0;
puts("Gimme Books' Titles:");
gets(temp);
while(temp[0] != '\x0'){
pin[index] = (char*)malloc(strlen(temp)+1);
strcpy(pin[index], temp);
index++;
gets(temp);
}
puts("\nBooks' List:");
for(int k = 0; k < index; k++){
puts(pin[k]);
}
}
Anyone here who can help me find out what I am doing wrong?
The link in the comments above [mostly] assumes that we know the number of elements before we allocate the array.
Thus, it's not as useful when we can only get the number of elements by reading the input file. For TTY input from stdin this won't work too well because we can't rewind the file.
A dynamic array is generally useful. So, I've created one that allows arbitrarily sized array elements. And, it can grow/expand as we add new elements.
And, for demo purposes here, I've created a "book" structure that stores Author's name and book title.
Here is the code. It is annotated:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
// general dynamic array control
typedef struct {
void *arr_base; // pointer to data
size_t arr_size; // bytes / element
size_t arr_count; // number of elements in use
size_t arr_capacity; // number of elements allocated
} arr_t;
// book control
typedef struct {
char *book_last; // author's last name
char *book_first; // author's first name
char *book_title; // book title
} book_t;
// arrnew -- allocate new array
arr_t *
arrnew(size_t siz)
{
arr_t *arr = calloc(1,sizeof(*arr));
// store the number of bytes in each element
arr->arr_size = siz;
return arr;
}
// arrappend -- get new element in array
// RETURNS: pointer to element
void *
arrappend(arr_t *arr)
{
size_t index;
void *ptr;
// get index of element to store into and increase the in use count
index = arr->arr_count++;
do {
// we have enough space for the new element already
if (arr->arr_count < arr->arr_capacity)
break;
// increase allocated amount
// NOTE: the increment is arbitrary
arr->arr_capacity += 10;
// grow the array
arr->arr_base = realloc(arr->arr_base,
arr->arr_capacity * arr->arr_size);
// got the larger array
if (arr->arr_base != NULL)
break;
perror("arrappend");
exit(1);
} while (0);
// point to element we can store into
ptr = arr->arr_base;
ptr += index * arr->arr_size;
return ptr;
}
// arrtrim -- trim array to number of elements actually used
void
arrtrim(arr_t *arr)
{
arr->arr_capacity = arr->arr_count;
arr->arr_base = realloc(arr->arr_base,arr->arr_capacity * arr->arr_size);
if (arr->arr_base == NULL) {
perror("arrtrim");
exit(1);
}
}
// arrfree -- free up array storage
void
arrfree(arr_t *arr)
{
free(arr->arr_base);
free(arr);
}
int
main(void)
{
char buf[300];
char *cp;
book_t *book;
// echo line if input is _not_ a tty [mostly for demo]
struct termios tio;
int echo = tcgetattr(fileno(stdin),&tio) < 0;
// get new array
arr_t *arr = arrnew(sizeof(book_t));
printf("Gimme Books's Titles:\n");
while (1) {
// get next line -- stop on EOF
char *cp = fgets(buf,sizeof(buf),stdin);
if (cp == NULL)
break;
// echo line if input is _not_ a tty
if (echo)
fputs(buf,stdout);
// strip newline
buf[strcspn(buf,"\n")] = 0;
// stop on blank line
if (buf[0] == 0)
break;
// get new book struct
book = arrappend(arr);
// get author's last name
char *tok = strtok(buf," \t");
book->book_last = strdup(tok);
// get author's first name
tok = strtok(NULL," \t");
book->book_first = strdup(tok);
// get the book title
tok += strlen(tok);
++tok;
for (; *tok != 0; ++tok) {
if (*tok != ' ')
break;
}
book->book_title = strdup(tok);
}
arrtrim(arr);
// show all the books
book = arr->arr_base;
for (size_t idx = 0; idx < arr->arr_count; ++idx, ++book)
printf("Last: %s First: %s Title: %s\n",
book->book_last,book->book_first,book->book_title);
// release storage for each book
book = arr->arr_base;
for (size_t idx = 0; idx < arr->arr_count; ++idx, ++book) {
free(book->book_last);
free(book->book_first);
free(book->book_title);
}
// release array storage
arrfree(arr);
return 0;
}
Here is the program input:
Lambstewer Abel A Tale of Two Cities
Smith John A baker's tale
Jones Fred Never On Sunday
Here is the program output:
Gimme Books's Titles:
Lambstewer Abel A Tale of Two Cities
Smith John A baker's tale
Jones Fred Never On Sunday
Last: Lambstewer First: Abel Title: A Tale of Two Cities
Last: Smith First: John Title: A baker's tale
Last: Jones First: Fred Title: Never On Sunday
I am trying to write text to a file using loops, but when I make it like (ogrenci+i) using i and not like (ogrenci+0) I'm getting some weird numbers and text in txt file.
When writing like this (ogrenci+0) it works correctly. What am I doing wrong?
I attent pointer to struct in a different function.
this is the question
QUESTIONS
Assume that you are given the structure below
typedef struct StudentMark {
char name[20];
char surname[20];
int midterm;
int final;
}STUDENT_MARK;
1-) Write down a program which contains
a-) A function to get the user entered name, surname, and exam marks into
dynamically
allocated STUDENT_MARK structure (your function MUST check input validity
i.e
entered marks must between [0..100]).
b-) A function to write down the entered VALID structures into a file
named as
marks_YOUR_STUDENT_ID.txt.
2-) Write a program which contains
a-) A function to read a file named as marks_YOUR_STUDENT_ID.txt which contains
STUDENT_MARK structures’ data.
b-) A function to calculate the average of each student’s exam marks and writes the result
onto screen as
“The student NAME SURNAME’s midterm mark is MIDTERM, final mark is
FINAL and his/her average is AVERAGE”
void girme (int studentnum){
int i;
studentnum = 2;
STUDENT_MARK *ogrenci;
ogrenci = (STUDENT_MARK*) malloc(studentnum * sizeof(STUDENT_MARK));
if(ogrenci == NULL) { exit(1); }
for(i=0;i<studentnum;i++)
{
printf("Enter the student's name, surname, midterm and final respectively: \n");
scanf("%s %s %d %d",(ogrenci+i)->name, (ogrenci+i)->surname, &(ogrenci+i)->midterm, &(ogrenci+i)->final);
if((ogrenci+i)->midterm > 100 || (ogrenci+i)->midterm < 0 || (ogrenci+i)->final > 100 || (ogrenci+i)->final < 0)
{
printf("midterm or final can not be higher than 100 or lower than 0 \n");
exit(1);
}
}
}
void yazma (int studentnum){
int i;
STUDENT_MARK *ogrenci;
FILE *dosya;
dosya = fopen("marks_190704033.txt","w");
if{ (dosya == NULL)
{
printf("Could not open file");
exit(1);
}
else
{
for(i=0;i<studentnum;i++)
{
fprintf(dosya, "%s %s %d %d", (ogrenci+0)->name, (ogrenci+0)-
>surname, (ogrenci+0)->midterm, (ogrenci+0)->final);
}
}
fclose(dosya);
}
int main()
{
int n =2;
girme(n);
yazma(n);
return 0;
}
STUDENT_MARK *ogrenci;
ogrenci = (STUDENT_MARK*) malloc(studentnum * sizeof(STUDENT_MARK));
ogrenci is a single pointer to the structure STUDENT_MARK to space allocated for several objects of struct STUDENT_MARK.
When using, f.e.:
(ogrenci+i)->name
in the for loop, you attempt to access not existing struct pointers to not existing structure objects.
Note: The compiler do not associate the allocated space with several pointers!
If you want to use pointer arithmetics like (ogrenci + i) you need to either define ogrenci as an array of pointers to STUDENT_MARK:
int studentnum = 5;
STUDENT_MARK *ogrenci[studentnum];
and initialize each pointer by the address of an existing structure object for which were each allocated space individually, f.e. like:
int studentnum = 5;
STUDENT_MARK *ogrenci[studentnum];
for(int i = 0; i < studentnum; i++)
{
ogrenci[i] = malloc(sizeof(*ogrenci));
}
or you define ogrenci as a pointer to pointer to STUDENT_MARK:
int studentnum = 5;
STUDENT_MARK **ogrenci;
ogrenci = malloc(sizeof(*ogrenci) * studentnum);
*ogrenci = malloc(sizeof(**ogrenci) * studentnum);
"When writing like this (ogrenci+0) it works correctly."
However, It "works" with 0 because ogrenci + 0 = ogrenci. There is no difference to ogrenci.
Side note: As you mabe have already seen, I omitted the cast of the returned pointer from malloc. This is because it is unnecessary and it might "add clutter" to your code: Do I cast the result of malloc
I am trying to improve my C skills so I apologize if my question is long. I am having a hard time understanding as to why my struct pointer holds the wrong value in my program, I tried to debug it but I am still relatively new to C and was hoping one of you could tell me what I'm doing wrong here and how I could improve my code and what to focus on.
I am making a program that stores user data on this struct and then prints it out.
typedef struct table {
char *firstName;
char *lastName;
int id;
}USER;
This function below stores the first name
void firstName(int *counter, int *check, USER *pt) {
for (int i = *counter; i < *check; i++) {
pt[i].firstName = calloc (MAX_LENGTH, sizeof(pt));
printf("Enter First Name: ");
getchar();
fgets(pt[i].firstName, MAX_LENGTH, stdin);
}
}
This is just my bool function returning true or false
bool isTrue(char *decision) {
if(*decision == 'Y') {
return true;
}
else {
return false;
}
}
And this is my main
int main(int argc, char **argv) {
USER *pt = calloc(1, sizeof(pt));
int counter = 0, check = 0;
char decision = '\0';
while (1) {
printf("Would you like to enter a user?(Y/N):");
fgets(&decision, 2, stdin);
strtok(&decision, "\n"); //remove the newline char
if (!isTrue(&decision)) {
break;
}
if (counter != 0) {
pt = realloc(pt, sizeof(pt) * 10); //the 10 is temporary
}
check = counter + 1; // make sure loop only runs once.
firstName(&counter, &check, pt);
++counter; // increment counter;
}
printStruct(pt, &counter);
return 0;
}
When I run it out sometimes it works fine and returns everything and sometimes it skips a value. This is what I get. It skips the value at pointer index 1 and prints garbage instead.
Would you like to enter a user?(Y/N):N
First name at array 0 is Ermir
First name at array 1 is P#1First name at array 2 is Kevin
First name at array 3 is Blaus
First name at array 4 is Adam
Also I was wondering why is it when I realloc here If i do I get a realloc error when I enter the second name.
if (counter != 0) {
pt = realloc(pt, sizeof(pt) * 10); //realloc(pt, sizeof(pt) * counter + 1) wont work
}
char decision = '\0';
...
fgets(&decision, 2, stdin);
You are only allocating 1 char but are at least reading 2 chars into it. Fix by allocating a sufficiently sized array for decision.
Unrelated but in firstName() pt[i].firstName = calloc (MAX_LENGTH, sizeof(pt)); should be pt[i].firstName = calloc (MAX_LENGTH, 1);
I have a defined array sample:
char *arguments[] = {"test-1","test-2","test-3"};
I am trying to add an argument input given by the command line. I tried the strcpy function and also to pass it through the array element e.g. arguments[num+1] = argv[1] but again not successfully.
I know that this is a very simple question but I am not an experienced programmer and all my experience comes from higher level programming languages (PHP, Perl).
The closest sample of work that I found online is C program to insert an element in an array and C program to delete an element from an array. But are not exactly what I am looking for and they are working with intigers not characters that I need.
My goal is to find a way to add and remove strings from a dynamic array that can grow and shrink based on the process of the script.
Thanks everyone for their time and effort to assist me.
Sample of a working code is given under:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* Set as minimum parameters 2 */
#define MIN_REQUIRED 2
#define MAX_CHARACTERS 46
/* Usage Instructions */
int help() {
printf("Usage: test.c [-s <arg0>]\n");
printf("\t-s: a string program name <arg0>\n");
printf("\t-s: a string sample name <arg1>\n");
return (1);
}
int main(int argc, char *argv[]) {
if ( argc < MIN_REQUIRED ) {
printf ("Please follow the instructions: not less than %i argument inputs\n",MIN_REQUIRED);
return help();
}
else if ( argc > MIN_REQUIRED ) {
printf ("Please follow the instructions: not more than %i argument inputs\n",MIN_REQUIRED);
return help();
}
else {
int size, realsize;
char *input = NULL;
char *arguments[] = {"test-1","test-2","test-3"};
int num = sizeof(arguments) / sizeof(arguments[0]);
printf("This is the number of elements before: %i\n",num);
int i;
for (i=0; i<num; i++) {
printf("This is the arguments before: [%i]: %s\n",i,arguments[i]);
}
printf("This is the input argument: %s\n",argv[1]);
printf("This is the array element: %i\n",num+1);
input = (char *)malloc(MAX_CHARACTERS);
if (input == NULL) {
printf("malloc_in failled\n");
exit(0);
}
memset ( input , '\0' , MAX_CHARACTERS);
int length_before = strlen(input);
printf("This is the length before: %i\n",length_before);
strcpy(input , argv[1]);
int length_after = strlen(input);
printf("This is the length after: %i\n",length_after);
//arguments[num+1] = input;
strcpy(arguments[num+1],input);
int num_2 = sizeof(arguments) / sizeof(arguments[0]);
printf("This is the number of elements after: %i\n",num);
for (i=0; i<num_2; i++) {
printf("This is the arguments after [%i]: %s\n",i,arguments[i]);
}
} // End of else condition
return 0;
} // Enf of int main ()
"My goal is to find a way to add and remove strings from a dynamic array":
char *arguments[] = {...} is statically allocated, so it cannot serve as a "dynamic array".
strcpy(arguments[num+1],input):
You cannot access arguments[num+1] when this array has only num entries.
Suggested fix - allocate and initialize arguments dynamically, according to the value of argc:
char* strings[] = {"test-1","test-2","test-3"};
int i, num = sizeof(strings) / sizeof(*strings);
char** arguments = malloc((num+argc-1)*sizeof(char*));
if (arguments == NULL)
; // Exit with a failure
for (i=0; i<num; i++)
{
arguments[i] = malloc(strlen(strings[i])+1);
if (arguments[i] == NULL)
; // Deallocate what's already been allocated, and exit with a failure
strcpy(arguments[i],strings[i]);
}
for (i=0; i<argc-1; i++)
{
arguments[num+i] = malloc(strlen(argv[i+1])+1);
if (arguments[num+i] == NULL)
; // Deallocate what's already been allocated, and exit with a failure
strcpy(arguments[num+i],argv[i+1]);
}
...
// Deallocate everything before ending the program
There are no dynamic arrays in C, arguments has a static size, capable of holding 3 elements,
strcpy(arguments[num+1],input);
is simply undefined behaviour, the expression arguments[num+1] accesses an array out of bounds (two elements after the last); no magical reallocation or something will happen.
In general, you have three options:
You have an upper bound of how many items you want to be able to store in the array and declare the array to have that size. Either keep track of the numbers actually stored in it or add some sentinel value (which needs additional space!) indicating the end.
You have an upper bound, and if the number of items you want to store happen to exceed this limit, you abort (returning an error indicator, telling the user that the input data is too big, …).
Look for malloc, realloc and free.