I had issue in below mention program to assign a value to the pointer.String concatenation Program( *s1=*s2) [closed]

StackOverflow https://stackoverflow.com/questions/23324186

Вопрос

While running below code i am getting error to assign the value to the s1 pointer

#include<stdio.h>

void concat(char*, char*);

//Main Program
void main(void)
{
    char str1[25], str2[25];
    printf("\nEnter First String:");
    gets(str1);
    printf("\nEnter Second String:");
    gets(str2);
    //Function call
    concat(str1, str2);
    printf("\nConcatenated String is %s", str1);
}

void concat(char *s1, char *s2) {
    // Checking Null character
    while (*s1 != '\0')
        s1++;
    //Checking Null character
    while (*s2 != '\0')
    {
        *s1 = *s2; //<-- Getting error in this line        
        s1++;
        s2++;
    }
    *s1 = '\0';
}
Это было полезно?

Решение

So you are getting access voilation....

The problem is that your buffers are probably overflowing and you have no length check in your code...

The buffers you have allocated are only 25 bytes long

char str1[25], str2[25];

so to intruduce a length check, add an extra parameter to concat which tells how long the output buffer is, like this

void concat(char *s1, char *s2, int len){
    // Checking Null character
    while (*s1 != '\0' && len > 0)
        s1++, len--;
    //Checking Null character
    while (*s2 != '\0' && len > 0)
    {
        *s1 = *s2; //<-- Getting error in this line        
        s1++;
        s2++;
        len--;
    }
    if (len > 0) // only set the null terminator if we have space
       *s1 = '\0';
}

an then call it as this

concat(str1, str2, 25);

An then also read the man page for strncat

Другие советы

because you are concatting str2 onto the end of str1, str1 needs to be large enough to hold the complete string, so you are problably overrunning str1, try

   char str1[25+25], str2[25];

The missing semi-colon after

  while(*s1!='\0')                                // Checking Null character
    s1++

is your problem, as the code is, the 2nd while loop will be executed everytime there is a character in s1.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top