简体   繁体   中英

construct my own strcat function with arrays in c

I am trying to write a function that works like strcat, I dont get any error when compiling the code. the problem is when calling the function it didnt append the elements in the second array to the first one. when I print the first array it still the same. any suggesting?

#include <stdio.h>
#include <string.h>

char *strcat1(char *dest, char *src);

char *strcat1(char *dest, char *src) {
    int i;
    int j;
    printf("i0=%d, j0=%d\n", i, j);

    i = strlen(dest);
    j = strlen(src);
    for (int z = 0; z < j; z++) {
        dest[z + i + 1] = src[z];    
    }
}

int main() {
    char str1[100];
    char str2[30];
    printf("put the first string:\n");
    fgets(str1, sizeof(str1), stdin);
    printf("\ninput the second string\n");
    fgets(str2, sizeof(str2), stdin);
    strcat1(str1, str2);
    printf("%s", str1);
}

str1 is finished by a '\\0'.

strlen returns length of string not including the terminating null character.

So for example if string is "toto" then strlen(string) is 4.

In memory :

string[0] = 't'
string[1] = 'o'
string[2] = 't'
string[3] = 'o'
string[4] = '\0'

But you are writing at dest[z+i+1] so in my example. string[z + 4 + 1] whitch is string[5]. So after the '\\0'.

The result will be : "toto\\0string2".

But because printf %s stop reading pointer at \\0, you only see "toto".

Try to replace

dest[z+i+1]

by

dest[z+i]

There is some confusion in given answer so far. It comes from fact that the strings read by fgets are not only null character terminated but also contain LINE_FEED character.

1) Coppying

dest[z+i+1]=src[z];  

has to be performed as:

dest[z+i-1] = src[z];  

to eliminate ' \\n' == 0x0A

or preserving '\\n' as:

dest[z+i] = src[z]; 

2) We also have to properly terminate the concatenated string.
Knowing that it i and j take under account '\\n' characters we have to terminated string accordingly:

   dest[i+j] = '\0' ;

3) In C90, the prototype is:

char *strcat(char *dest, const char *src);

The strcat() function shall return the pointer dest ; the function has no failure mode and no error return.

The improved program:

#include <stdio.h>
#include <string.h>

char* strcat1(char* dest, const char* src);

char* strcat1(char* dest, const char* src){
   size_t i;
   size_t j;
   size_t z;

   i = strlen(dest);   //  Note: '\n' is included in the length count
   j = strlen(src);    //  Note: '\n' is included in the length count

   printf("i0=%zu, j0=%zu %X\n ", i, j, src[j-1] );

   for(z=0; z < j; z++){
        dest[z+i] = src[z];    
   }
   dest[i+j] = '\0' ;

  return dest;
}

int main(void){

   char str1[100];
   char str2[30];

   printf("put the first string:\n");
   fgets(str1, sizeof(str1), stdin);

   printf("\ninput the second string\n");
   fgets(str2, sizeof(str2), stdin);

   strcat1(str1,str2);

   printf("\n%s", str1);

   return 0;
}

Output:

put the first string:                                                                                                                           
1234                                                                                                                                            

input the second string                                                                                                                         
567890                                                                                                                                          
i0=5, j0=7 A                                                                                                                                    

1234                                                                                                                                            
567890                                                                                                                                          

There are some problems with your strcat1 function:

  • The prototype should be char *strcat1(char *dest, const char *src); as the function does not modify the source string.

  • The characters should be copied at offset z + i into the dest array. You currently copy the source string after the null terminator, so nothing appears when you print the destination array after the copy.

  • You must copy the null terminator too, to ensure proper termination of the destination array.

  • You must return the pointer to the destination array.

  • The index variables should have type size_t , that has a larger positive range than type int .

Here is a modified version:

char *strcat1(char *dest, const char *src) {
    size_t i = strlen(dest);
    size_t j = strlen(src);
    for (size_t z = 0; z <= j; z++) {
        dest[z + i] = src[z];    
    }
    return dest;
}

Note that you can implement this function with pointers, without strlen and with a single scan of the source string:

char *strcat1(char *dest, const char *src) {
    char *p = dest;
    while (*p)
        p++;
    while ((*p++ = *src++) != '\0')
        continue;
    return dest;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM