书写和打印两个字符串在每个字符串之间交替组合时出现分段错误?

时间:2018-12-02 01:25:06

标签: c

目标是采用两个字符串(最多30个字符),例如“ cat”和“ dog”,并打印出“ cdaotg”(在字符串之间交替)。如果一个字符串较长,则应打印其余较长的字符串。 写字符串或打印字符串时出现段错误(核心转储)错误,这是相关代码。

#include <stdio.h>

int main(int argc, char *argv[])
{
    char str1[30], str2[30], newstr[61] = { '\0' };     //declarations
    printf("Please enter a maximum 30 characters: ");   //user input
    scanf("%s", str1);
    printf("Please enter a maximum 30 characters: ");
    scanf("%s", str2);

    if (*argv[1] == 'i') {     //if statement to check if command argument is 'i'
        char *newstr;   //declare pointer to first element of array "newstr"
        while (*str1 != '\0') {      // while the first string is not NULL 
            *newstr = *str1;      //value at newstr=value at str1
            newstr++;         //increment pointer
            *newstr = *str2;        //value at newstr=value at str2
        }
        *newstr = '\0'; //set the rest of newstr to null
        printf("The combined string is: %s", newstr);     //print out combined string 
    }
    else  //if command argument!='i', just print out nope
        printf("nope");
}

1 个答案:

答案 0 :(得分:0)

您必须修复顶部注释中提到的一些错误。

但是,不要使用子范围的char *newstr;。它隐藏了上面的char newstr[61]定义(您要做要使用)。

您的合并代码需要一些工作:

char *dst = newstr;
const char *s1 = str1;
const char *s2 = str2;

for (;  (*s1 != 0) && (*s2 != 0);  ++s1, ++s2) {
    *dst++ = *s1;
    *dst++ = *s2;
}

for (;  *s1 != 0;  ++s1)
    *dst++ = *s1;

for (;  *s2 != 0;  ++s2)
    *dst++ = *s2;

*dst = 0;