码迷,mamicode.com
首页 > 其他好文 > 详细

关于argv和strncpy()的困惑

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

标签:style   blog   color   io   for   ar   问题   div   

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

不清楚是哪里的问题。

 

#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()的困惑

标签:style   blog   color   io   for   ar   问题   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!