antil - 1 year ago 91
C Question

# I want to ask my failed code.

This is a exercise in teach yourself c in 21days.

The question is : Write a function that accepts two strings. Use the malloc() function to allocate enough memory to hold the two strings after they have been concatenated. Return a pointer to this new string.

So, I was make First code. but dosen't operate. The function in code is following :

`````` char *concate(char *p, char *q)
{
int i, len;
char *r;

if((r = (char *)malloc(100)) == NULL){
printf("Allocate failed\n");
exit(1);
}

r = p;
for(i = 0; r[i] != '\0'; ++i)
;
len = i;
for(i = 0; q[i] != '\0'; ++i, ++len)
r[len] = q[i];

return r;
}
``````

There are no compile error but run-time error.

Because i want only use pointer variable solve this problem.

But i have no idea, use following code solved problem.

``````char *concate(char *p, char *q)
{
int i, len;
char *r;

if((r = (char *)malloc(1000)) == NULL){
exit(1);
}

for (i = 0; p[i] != '\0'; ++i)
r[i] = p[i];

len = i;

for(i = 0; q[i] != '\0'; ++i, ++len)
r[len] = q[i];

r[len] = '\0';

return r;
}
``````

This code can run, and can have i wanted result.

My question is, How can i only use pointer variable get result?

I want use *p, *q, *r and pointer arithmetic and some variable( i for loop).

I solved problem, but feel not good, because i use array solved this.

Firstly, you are allocating the memory of 100 as a random value, hoping it is enough. It is a better approach to find the length of each string and allocate memory for the combined length.

Secondly, you are overwriting the pointer to the allocated memory by using `r = p;` You need to use `strcpy` to copy the string from `r` to `p`.

Here is a solution using only pointers

``````char *concate(char *p, char *q)
{
int i, len=0, ;
char *r, *temp;

temp = p;
for(; *temp ; ++temp)
len++;
temp = q;
for(; *temp ; ++temp)
len++;

if((r = malloc(len+1)) == NULL){
printf("Allocate failed\n");
exit(1);
}

for (temp = r; *p; p++, temp++)
*temp = *p;

for (; *q; q++, temp++)
*temp = *q;

*temp = '\0';

return r;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download