can anyone explain malloc and how it can be used when trying to input a set of strings and then outputing a set of strings
can anyone explain malloc and how it can be used when trying to input a set of strings and then outputing a set of strings
Is this
0. a known number of strings of fixed length?
1. a known number of strings of variable length?
2. an unknown number of strings of variable length?
3. an unknown number of strings of fixed length?
And can you do this using char arrays?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I am trying to use it in a program that takes in a user input of a any lentgh string, the user will use up to 10 strings, then I was going to store them into an array type; and output from an array type; using a for loop of course.
Thanx jpre
Hey,
I don't know if its actually possible to take in an array of any size.
(unless you take it in as a command line argument).
There needs to be a maximun value for the size of the input string.
Or you could possibly use malloc.. but that would require the user to enter any number of smaller string (fixed size) then you could join all the strings together into a larger string using malloc.
of course i could be wrong. this is how i understand it though.
hope i helped!
ActionMan
"THE DAY IS MYNE!!!!
I'll take famouse titties for $400"
-Sean Connery, Saturday Night Live
> takes in a user input of a any lentgh string, the user will use up to 10 strings
This is a simple implementation - if lines are longer than BUFSIZ, it will need some modification.
Code:#include <stdio.h> #include <string.h> #define MAX_LINES 10 int main ( ) { char buff[BUFSIZ]; char *lines[MAX_LINES]; int i; for ( i = 0 ; i < MAX_LINES ; i++ ) { fgets( buff, BUFSIZ, stdin ); lines[i] = malloc( strlen(buff) + 1 ); strcpy( lines[i], buff ); } return 0; }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.