I am trying to figure out how to take in a couple strings, then store them into a place in memory, then call that memory and put into a function, so that it can print all strings, I believe this is how malloc is used
thanx vry
This is a discussion on string and malloc within the C Programming forums, part of the General Programming Boards category; I am trying to figure out how to take in a couple strings, then store them into a place in ...
I am trying to figure out how to take in a couple strings, then store them into a place in memory, then call that memory and put into a function, so that it can print all strings, I believe this is how malloc is used
thanx vry
Here is a trivial example:
This is a trivial example in which you can do so many different ways. I just chose a quick way.Code:#include <stdio.h> #include <stdlib.h> void put_string(char *s); main() { char *c; c = (char *)malloc(20 * sizeof(char)); printf("Enter String: "); gets(c); printf("The string you entered was:\n"); put_string(c); system("PAUSE"); return 0; } void put_string(char *s) { while (*s != '\0') printf("%c", *s++); printf("\n"); }
I include <stdlib.h> for the use of the malloc() & system() functions, <stdio.h> for printf(), gets(), etc..
This is how malloc() works. It first allocates an amount of memory specified, in this case: 20 units the size of a char. Then malloc returns a pointer to that space created. You then must type-cast the pointer returned to (char *) b/c since you used sizeof() it will return a type of size_t.Code:char *c; c = (char *)malloc(20 * sizeof(char));
Then gets() is a handy function that takes in characters until it has found a newline ('\n') character. It then stores that string (minus the '\n') into a pointer.
Then our makeshift put_string() function is simple. Just write a function that takes a character pointer argument and then walk along the string printing each character in the string. Then printf() a '\n' and voila.
NOTE: There is a function in the C standard library called puts() that does the exact same thing has our makeshift put_string.
Have fun and I hoped this helped.