为什么这个程序不打印串联字符串?

时间:2016-11-04 12:38:01

标签: c

连接字符串的代码

    #include<stdio.h>
    char *concat(char *p1,char *); //function decalaration
    int main(void)
    {
        char a[100],b[100],*q=NULL;  //declare two char arrays
        printf("Enter str1:");
        scanf("%s",a);
        printf("Enter str2:");
        scanf("%s",b);
        q=concat(a,b);     //calling str concat function
        printf("Concatenated str:%s\n",q);
        return 0;
    } 
    char *concat(char *p1,char *p2) //function to concatenate strings 
    {
        while(*p1!='\0')
        p1++;
        while(*p2!='\0')
        {
                *p1=*p2;
                p1++;
                p2++;
        }
        *p1='\0';
        printf("Concatenated str=%s\n",p1); //printing the concatenated string
        return p1; //returning pointer to called function
    }

//虽然逻辑正确但它没有显示输出。 //为什么这段代码不起作用?

2 个答案:

答案 0 :(得分:5)

您正在返回 char *concat(char *p1,char *p2) //function to concatenate strings { char *org = p1; ... return org; } ,它不指向连接字符串的开头。您只需要保存原件并将其退回。

Order Number        Operation          Sequence
A1                  0                  1
A1                  0                  2
A1                  L                  3
A1                  L                  4
A2                  L                  1
A2                  0                  2
A3                  L                  1
A4                  0                  1
A4                  L                  2
A4                  L                  3
A4                  L                  4                  

答案 1 :(得分:1)

你可以试试这个:

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

#define MAXCHAR 100

void trim_newline(char *str);
char *concatenate(const char *str1, const char *str2);
void exit_if_null(void *ptr, const char *msg);

int
main(void) {
    char str1[MAXCHAR], str2[MAXCHAR];
    char *concat;

    printf("Enter str1: ");
    if (fgets(str1, MAXCHAR, stdin) != NULL) {
        trim_newline(str1);
    }

    printf("Enter str2: ");
    if (fgets(str2, MAXCHAR, stdin) != NULL) {
        trim_newline(str2);
    }

    concat = concatenate(str1, str2);

    printf("Concatenated str:%s\n",concat);

    free(concat);

    return 0;
}

void
trim_newline(char *str) {
    int length = strlen(str) - 1;

    if (str[length] == '\n') {
        str[length] = '\0';
    }
}

char 
*concatenate(const char *str1, const char *str2) {
    char *result;

    result = malloc(strlen(str1) + strlen(str2) + 1);
    exit_if_null(result, "Initial Allocation");

    strcpy(result, str1);
    strcat(result, str2);

    return result;
}

void
exit_if_null(void *ptr, const char *msg) {
    if (!ptr) {
        printf("Unexpected null pointer: %s\n", msg);
        exit(EXIT_FAILURE);
    }
}