I'm trying to concatenate two strings together with pointers without using any of the functions.When I enter the two strings for example first hello and then world the output is
hello
world
and not helloworld.Any help would be appreciated.
#include<stdio.h>
#include<stdlib.h>
int main(){
char *s=(char *)malloc(sizeof(char *));
char *s2=(char *)malloc(sizeof(char *));
fgets(s,10,stdin);
fgets(s2,10,stdin);
int i=0;
while(*s){
s ;
i ;
}
while(*s2!='\0'){
*s=*s2;
s ;
s2 ;
i ;
}
*s='\0';
printf("%s",s-i);
}
CodePudding user response:
The program has undefined behavior because you did not allocate memory for entered strings.
char *s=(char *)malloc(sizeof(char *));
char *s2=(char *)malloc(sizeof(char *));
fgets(s,10,stdin);
fgets(s2,10,stdin);
You only allocated memory for two pointers ( sizeof(char *)
).
You need to allocate memory large enough that can contains entered strings and their concatenation in the first character array.
The function fgets
can append the new line character '\n' to an entered string. You need to overwrite it.
Also you should not change the original pointers because you need to use them to free the allocated memory.
And take into account that the result string will contain at least 11
characters including the terminating zero character '\0'
instead of 10
characters if you are going to enter "hello"
and "world"
and concatenate them. Though in general it is better to reserve 13
characters if the entered strings will not contain the new line character.
The program can look for example the following way
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
enum { N = 7 };
char *s1 = malloc( 2 * N - 1 );
char *s2 = malloc( N );
s1[0] = '\0';
s2[0] = '\0';
fgets( s1, N, stdin );
fgets( s2, N, stdin );
char *p1 = s1;
while (*p1 != '\n' && *p1 != '\0') p1;
for (char *p2 = s2; *p2 != '\n' && *p2 != '\0'; p2)
{
*p1 = *p2;
}
*p1 = '\0';
puts( s1 );
free( s1 );
free( s2 );
}
The program output might be
hello
world
helloworld
Instead of these lines
char *s1 = malloc( 2 * N - 1 );
char *s2 = malloc( N );
s1[0] = '\0';
s2[0] = '\0';
you could write
char *s1 = calloc( 2 * N - 1, sizeof( char ) );
char *s2 = calloc( N, sizeof( char ) );
The arrays are zero initialized to keep empty strings in case when calls of fgets will be interrupted.
CodePudding user response:
fgets()
reads to the end of the file or end of line, but includes the end of the line in the data read.
So in your case, you are also concatenating the string with the new lines.
On a different note your statement char *s=(char *)malloc(sizeof(char *));
is allocating memory for sizeof(char*)
characters i.e.: the size of a pointer, not X number of characters.
Also since you are concatenating one 10 character string t another, the string needs to be allocated to hold at least that (20 chars 1 null).