首页 > 其他 > 详细

关于argv和strncpy()的困惑

时间:2014-08-14 23:37:36      阅读:369      评论:0      收藏:0      [点我收藏+]

遇到一个问题,命令行参数复制到字符串后打印出来的结果与直接打印命令行参数的结果不一致。

不清楚是哪里的问题。

 

#include <stdio.h>
#include <string.h>
#define LEN 5
int main(int argc, char* argv[])
{
    char s1[LEN];
    char s2[LEN];

    for(int i = 0; i<LEN; i++)
    {
        s1[i] = \0;
        s2[i] = \0;
    }

    printf("%s\n%s\n", s1, s2);

    // 直接打印命令行参数
    for(int i = 1; i < argc; i++)
        printf("%s\n", argv[i]);

    // 将命令行参数复制到字符串再打印
    strncpy(s1, argv[1], LEN);
    strncpy(s2, argv[2], LEN);
    printf("%s\n%s\n", s1, s2);

    return 0;
}

 

运行:

test.exe tmp temp

结果是对的:



tmp
temp
tmp
temp

但是,运行:

test.exe tmp tempmoreword

结果:



tmp
tempmoreword
tmp
tempmtmp

即,命令行参数超出strncpy()指定的字符串长度时会出错。

关于argv和strncpy()的困惑,布布扣,bubuko.com

关于argv和strncpy()的困惑

原文:http://www.cnblogs.com/stayathust/p/3913453.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!