string combining

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • logantr
    New Member
    • Mar 2012
    • 11

    #1

    string combining

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    void interpose(char s[], char a[], int pos)
    {
    	char b[80];
    	int j=0;
    	int l=0;
    	for(int i=pos;s[i]!='\0';i++)
    
    	{
    		b[j]=s[i];
    		j++;
    	}
    	b[j]='\0';
    	for(int c=0;a[c]!='\0';c++)
    	{
    		s[pos]=a[c];
    		pos++;
    	}
    	for (int k=pos;b[l]!='\0';pos++)
    	{
    		s[pos]=b[l];
    		l++;
    	}
    	s[pos]='\0';
    }
    
    int main()
    {
    	char str1[80];
    	char str2[80];
    	int posi;
    	printf("String1:\n");
    	gets(str1);
    	printf("String2:\n");
    	gets(str2);
    	printf("Sayıyı giriniz");
    	scanf("%d", &posi);
    	interpose(str1,str2,posi);
    	puts(str1);
    
    	
    	return 0;
    }
    The program should take 2 string parameter and 1 int parameter for combining. (without any str functions, the functions should be written by coder)

    my problem is when i enter int value program crashes.
    For example,
    str1='Good';
    str2=' Morning';
    int x= 5;
    The output will be 'Good Morning'
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    If you call interpose() with these arguments:
    interpose("Good ", "Morning", 5);

    then from line 5, s points at "Good" and line 10 is equivalent to
    Code:
    for (i=5; s[i]!='\0'; i++)
    
    s[0] == 'G'
    s[1] == 'o'
    s[2] == 'o'
    s[3] == 'd'
    s[4] == '\0'
    s[5] is beyond the end of the array, and this access thus causes undefined behavior.
    Last edited by Frinavale; Mar 26 '12, 04:57 PM.

    Comment

    • logantr
      New Member
      • Mar 2012
      • 11

      #3
      Done.Thank to you for satisfying answer.

      Comment

      Working...