Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

scanf and Malloc Help

Status
Not open for further replies.

OOzy

Programmer
Jul 24, 2000
135
SA
How can I prompt the user to enter two strings then concatenates the two strings and use the malloc() function to allocate enough memory to hold the two strings after they have been concatenated.
Then return a pointer to this new string.

For example, if I pass "hello " and "world!", the function returns a pointer to "Hello world!".

 
Use fgets() to get the strings from the user, storing each string in a separate array of char (scanf() can be used too, but fgets() is much better suited for grabbing strings from the user).

Pass the strings to your "concatenation" function

Use strlen() in the function to compute the length of each string and add the lengths together.

Use malloc() to allocate memory based on the total lengths of the strings + 2 (for the terminating null and the space between the strings).

Use sprintf() or strcpy()/strcat() to copy the strings into the allocated buffer.

Return a pointer to the resultant string.

To get you started, the top of your "concatenation" function should look like this:

char *
concatStrings(const char *s1,const char *s2)
{
char *result;
size_t len=strlen(s1)+strlen(s2);

result=malloc(len+1);

if (result!=NULL) {
/* Copy the strings to result */

If you need further help, post your best attempt.


Russ
bobbitts@hotmail.com
 
char *chrptr;
printf("Enter the first String");
gets(string1);
printf("Enter the second String");
gets(string2);

chrptr = (char *) malloc(sizeof(strlen(string1)+strlen(string2)));


if(chrptr!=NULL)
// perform concatenation.
....
SwapSawe.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top