C - using malloc to dynamically assign memory for a array of strings

Joined
Nov 2, 2008
Messages
1
Reaction score
0
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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top