LINUX.IE, website of the Irish Linux Users' Group
Tux rules!

   
Home
New Users
Articles
Download
Projects
Community
Vendors

  Print Version
Email to...
 
Archives:


planetILUG

Recent News

News Archive


Join the
ILUG
on FaceBook


Join the
ILUG
on LinkedIn


Join the
ILUG SETI
Group



















 
 :: Mailing Lists

[ILUG] C string concat question revisited

[ILUG] C string concat question revisited

Dave Neary dave.neary at palamon.ie
Tue Jul 3 09:56:36 IST 2001


Conor Daly wrote:
> 
> Some while back, Kevin posted the above which allocates *new* memory for a
> string s which contains s1 and s2 (useage: s = strdup2(s1, s2); ).
> Now, I have a string struct.s which, as the name suggests, is part of an
> already allocated struct.  If I want to set *that* to contain s1 and s2, can
> I use the above ( struct.s = strdup2(s1, s2); ) or do I just use strncpy()
> and strncat()?

No reason why you can't, if you're sure it'll work :)

An alternate (possibly slightly less messy) solution would be

char * mystrdupcat(char *s1, char *s2)
/* Note all functions starting with "str" are forbidden by the standard
*/
{
	char *string;
	int l1, l2;

	l1 = strlen(s1);
	l2 = strlen(s2);

	str = malloc(l1 + l2 + 1);
	/* Error checking stuff... */

	strncpy(str, s1, l1 + 1); /* Copies the '\0' terminator'
	strncat(str, s2, l2 + 1); /* Over-writes '\0' and writes its own */

	return str;
}

Cheers,
Dave.

-- 
David Neary,               E-Mail dave.neary at palamon.ie
Palamon Technologies Ltd.  Phone +353-1-634-5059




More information about the ILUG mailing list
Read this without the formatting.
                                                                                                    

 

Hosted by HEAnet


Maintained by the ILUG website team. The aim of Linux.ie is to support and help commercial and private users of Linux in Ireland. You can display ILUG news in your own webpages, read backend information to find out how. Networking services kindly provided by HEAnet, server kindly donated by Dell. Linux is a trademark of Linus Torvalds, used with permission. No penguins were harmed in the production or maintenance of this highly praised website. Looking for the Indian Linux Users' Group? Try here. If you've read all this and aren't a lawyer: you should be!
RSS Version
Powered by Dell