c - Garbage values; strange string strlen value -


i trying write function inserts 1 string string @ specified value. returning few garbage values toward end of new string, presumably because, reason, strlen of new string greater should be; strlen(combo) should equal s1 + s2 not. not sure why returning 13 instead of 9 length. here's code:

#include <stdio.h> #include <string.h>  void insertstring(char *string1, char *string2, int position) {     int i, j = 0, k = 0, s1 = strlen(string1), s2 = strlen(string2);     char combo[s1 + s2];      (i = 0; < s1 + s2; i++) {         combo[i] = i;     }      (i = 0; < s1 + s2; i++) {         if (i < position) {             combo[i] = string1[i];             j++;         }         else if (i >= position && < position + s2) {             combo[i] = string2[k];             k++;         }         else if (i >= position + s2) {             combo[i] = string1[j];             j++;         }     }     (i = 0; < strlen(combo); i++){         printf("%c", combo[i]);     }      printf ("\n combolength = %lu\n", strlen(combo));     printf ("s1 = %d\n", s1);     printf ("s2 = %d\n", s2); }   int main (void) {     insertstring("i pie", "like", 2);      return 0; } 

edit: added null character. still returning single garbage value several spaces right of new string, , still not returning 9 proper string length.

#include <stdio.h> #include <string.h>  void insertstring(char *string1, char *string2, int position) {     int i, j = 0, k = 0, s1 = strlen(string1), s2 = strlen(string2);     char combo[s1 + s2];      (i = 0; <= s1 + s2; i++) {         combo[i] = i;     }      (i = 0; < s1 + s2; i++) {         if (i == s1 + s2) {             combo[i] = '\0';         }         else if (i < position) {             combo[i] = string1[i];             j++;         }         else if (i >= position && < position + s2) {             combo[i] = string2[k];             k++;         }         else if (i >= position + s2) {             combo[i] = string1[j];             j++;         }     }     (i = 0; < strlen(combo); i++){         printf("%c", combo[i]);     }      printf ("\n combolength = %lu\n", strlen(combo));     printf ("s1 = %d\n", s1);     printf ("s2 = %d\n", s2); }   int main (void) {     insertstring("i pie", "like", 2);      return 0; } 

you lacking terminating \0 in combo string. strlen() returns length excluding terminating null-byte.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -