here is my code

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

int main()
{
    char A1[100], A2[100],c[100];
    int n1,n2,i,j;
    printf("Enter string A1:\n");
    gets(A1);
    printf("Enter string A2:\n");
    gets(A2);
    n1=strlen(A1); printf("%d ",n1);
    n2=strlen(A2); printf("%d ",n2);
    char *p1=A1, *p2=A2, *p;
    p=(char*)malloc((n1+n2)*sizeof(char));
    for(i=0;i<n1; i++)
    {
     *(p+i) = *(p1+i);
     
     }
    for(i=0; i<n2; i++)
    {
     *(p+n1+i)=*(p2+i); 
    }
    
    int k2=strlen(p);
    printf("%d ",k2); // i try to print out the length of array to know if it's true or not but it's always greater than true length
    printf("%s",p); 
    getch();
    return 0;
}

after I run it, the string printed is added with some unsual charater.
I allocated the memory for string number 3 (p) but actually, it's is greater than needed
I don't know why
hepl me solve it
Thank you

Recommended Answers

All 2 Replies

You need a terminating null character, \0. You could add it any number of ways. If you just change "for(i=0; i<n2; i++)" so that "i" goes from 0 to "n2" then it will copy the null at the end of the second string to your new string.

You need a terminating null character, \0. You could add it any number of ways. If you just change "for(i=0; i<n2; i++)" so that "i" goes from 0 to "n2" then it will copy the null at the end of the second string to your new string.

ukie! Thank you very much! I've got it ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.