Reputation: 25
I'm a bit of a newbie at C, so please bear with me...
I have a function to count char in a string called char strLength
, but I have to create a function that uses this function to count the number of characters in a passed string, mallocates a new string with space for a NULL terminator, copies the string and then returns the copy.
Here's what I have:
character counter
int strLength(char* toCount)
{
int count = 0;
while(*toCount != '\0')
{
count++;
toCount++;
}
return count;
}
and here's the beginning of the sought-after function
char* strCopy(char *s)
{
int length = strLength(s);
}
Upvotes: 0
Views: 74
Reputation: 3891
You can use strdup() clib call.
You can write something like:
char* strCopy(char *s) { int length = strLength(s); char *rc = (char *)malloc(length + 1); return rc? strcpy(rc, s) : NULL; }
Upvotes: 0
Reputation: 40254
You want strdup
. However, since I suspect this is a learning exercise:
char *strCopy(const char *src)
{
size_t l = strlen(src) + 1;
char *r = malloc(l);
if (r)
memcpy(r, src, l);
return r;
}
If you are curious how to copy strings yourself, you could replace the memcpy
with something like:
char *dst = r;
while (*src)
*dst++ = *src++;
*dst = 0;
However I would suggest using library functions: if not strdup
, then malloc
+ memcpy
.
Upvotes: 0
Reputation: 726929
Since you are struggling with malloc
, here is how the next line should look:
char* strCopy(char *s)
{
int length = strLength(s);
char *res = malloc(length+1);
// Copy s into res; stop when you reach '\0'
...
return res;
}
Upvotes: 1