Hi,
I've been having some difficulty with a C assignment that I have (I'm starting to realize how much PHP and Java spoils me!). Its a simple cash register that asks for the type of purchase, then for a description and price. Below is what I've written so far. The big problem that I am having is how to create the arrays (or arrays of pointers really) to dynamically assign memory at run time, to be able to collect the information from multiple selections (obviously right now only the last description and price that are inputted are stored).
My understanding is that I need to use malloc in dynamically store the descriptions as they are entered. As strings (array of chars right?) need to have \0 at the end to signify the end of the string I add one to whatever the length of the string that I want to store is. Was hoping someone would be able to tell me if I have the right idea or am I totally all over the place?
Code below.
Grateful for any suggestions
Soap
I've been having some difficulty with a C assignment that I have (I'm starting to realize how much PHP and Java spoils me!). Its a simple cash register that asks for the type of purchase, then for a description and price. Below is what I've written so far. The big problem that I am having is how to create the arrays (or arrays of pointers really) to dynamically assign memory at run time, to be able to collect the information from multiple selections (obviously right now only the last description and price that are inputted are stored).
My understanding is that I need to use malloc in dynamically store the descriptions as they are entered. As strings (array of chars right?) need to have \0 at the end to signify the end of the string I add one to whatever the length of the string that I want to store is. Was hoping someone would be able to tell me if I have the right idea or am I totally all over the place?
Code below.
Code:
void addtoarray(char* data)
{
index++;
array[index] = malloc(strlen(data) + 1);
strcpy(&array[index], data);
free(data);
}
Code:
#include <stdio.h>
#include <conio.h>
int main()
{
int index = 0;
int selection;
char str[256];
float cost;
do{
printf("Please enter your choice of operation 1-3:");
scanf("%d", &selection);
switch(selection)
{
case 1:printf("\n enter description \n");
fflush(stdin);
gets(str);
printf("\n enter price \n");
fflush(stdin);
scanf("%f", &cost);
break;
case 2: printf("\n enter description \n");
fflush(stdin);
gets(str);
printf("\n enter price \n");
fflush(stdin);
scanf("%f", &cost);
break;
case 3: printf("\n enter description \n");
fflush(stdin);
gets(str);
printf("\n enter price \n");
fflush(stdin);
scanf("%f", &cost);
break;
break;
case 4:selection=4;
printf("description : %s\n", &str);
printf("price : %0.2f\n", cost);
break;
}
} while(selection != 4);
return 0;
}
Grateful for any suggestions
Soap