lluvio 发表于 2020-10-4 11:10:57

字符串处理函数的问题

为什么这里str6出问题但是str4没事呢?

lluvio 发表于 2020-10-4 11:11:48

char str1[] = "ABCDEFGHIJKLMN";
    char str2;char str3;
    char str4;char str5;
    char str6;

    strncpy(str2, str1, sizeof(str2));
    printf("strlen str2 = %u\n",strlen(str2));

    strncpy(str3, str2, 5);      str3 = '\0';
    strncpy(str4, str2, 6);
    printf("strlen str4 = %u\n", strlen(str4));
    strncpy(str5, str2, 7);
    strncpy(str6, str2, 4);      //str6 = '\0';
    printf("strlen str6 = %u\n", strlen(str6));

    printf("str1 = %s\n", str1);
    printf("str2 = %s\n", str2);
    printf("str3 = %s\n", str3);
    printf("str4 = %s\n", str4);
    printf("str5 = %s\n", str5);
    printf("str6 = %s\n", str6);

巴巴鲁 发表于 2020-10-4 11:43:06

str5和str6复制过来后都没有加'\0',后面会输出乱码
char str1[] = "ABCDEFGHIJKLMN";
    char str2;char str3;
    char str4;char str5;
    char str6;

    strncpy(str2, str1, sizeof(str2));
    printf("strlen str2 = %u\n",strlen(str2));

    strncpy(str3, str2, 5);      str3 = '\0';
    strncpy(str4, str2, 6);
    printf("strlen str4 = %u\n", strlen(str4));
    strncpy(str5, str2, 7);      str5 = '\0';//加'\0'
    strncpy(str6, str2, 4);      str6 = '\0'; // 加'\0'
    printf("strlen str6 = %u\n", strlen(str6));

    printf("str1 = %s\n", str1);
    printf("str2 = %s\n", str2);
    printf("str3 = %s\n", str3);
    printf("str4 = %s\n", str4);
    printf("str5 = %s\n", str5);
    printf("str6 = %s\n", str6);

当初约定 发表于 2020-10-4 11:47:15


我用你的源码测试了一下,感觉没问题啊

当初约定 发表于 2020-10-4 11:48:09

#include<stdio.h>
#include<string.h>
int main()
{
        char str1[] = "ABCDEFGHIJKLMN";
    char str2;char str3;
    char str4;char str5;
    char str6;

    strncpy(str2, str1, sizeof(str2));
    printf("strlen str2 = %u\n",strlen(str2));

    strncpy(str3, str2, 5);      str3 = '\0';
    strncpy(str4, str2, 6);
    printf("strlen str4 = %u\n", strlen(str4));
    strncpy(str5, str2, 7);
    strncpy(str6, str2, 4);      //str6 = '\0';
    printf("strlen str6 = %u\n", strlen(str6));

    printf("str1 = %s\n", str1);
    printf("str2 = %s\n", str2);
    printf("str3 = %s\n", str3);
    printf("str4 = %s\n", str4);
    printf("str5 = %s\n", str5);
    printf("str6 = %s\n", str6);
        return 0;
}

巴巴鲁 发表于 2020-10-4 12:04:02

当初约定 发表于 2020-10-4 11:47
我用你的源码测试了一下,感觉没问题啊

奇怪,是编译器不一样吗?我str5和str6后面都输出乱码
页: [1]
查看完整版本: 字符串处理函数的问题