zoukankan      html  css  js  c++  java
  • 使用c函数库的两个函数strtok, strncpy遇到的问题记录

    1. strtok

    问题背景: 解析形如 “1,2,3,4,5”字符串到整数数组

    (1)计算个数

    char* delim = ",";

    int count = 0;

    int *numbers = NULL;

    char* str = "1,2,3,4,5";

    char* token = strtok(str,delim);

    while(token){

      count++;

      token = strtok(NULL, delim);

    }

    (2)申请内存,记录数字

    numbers = (int*)malloc(sizeof(int)*count);

    token = strtok(str, delim);

    int index = 0;

    while(token){

      numbers[index++] = atoi(token);

      token = strtok(NULL, delim);

    }

    问题记录:strtok()函数修改了str字符串本身,所有逗号被改成了‘’。因此(2)里面再用strtok操作str字符串将出现问题

    2. strncpy

    问题背景: 字符串拷贝

    struct  A{

    char ifname[16];

    char a;

    char b;

    }

    char c[32] = {0};

    strncpy(c, "abcdef", 32-1);

    strncpy(A.ifname, c, 32-1);

    问题记录:第二个拷贝会修改 A.a 的值,改成空字符, 因为strncpy当遇到空字符拷贝结束时,若拷贝个数未达到第三个参数count,则使剩余的为空字符,直到count个数。

    注:strncpy(dest, src, count),count的长度不要超过dest所能容纳的最大字符数,若为字符串,最大应为count-1更保险。

  • 相关阅读:
    ZOJ 3795 Grouping
    ZOJ 3791 An Easy Game
    ZOJ 3790 Consecutive Blocks
    POJ 1451 T9
    POJ 1141 Brackets Sequence
    POJ 2411 Mondriaan's Dream
    POJ 2513 Colored Sticks
    Eclipse 快捷键大全
    C# lock关键字(多线程)
    C# 内部类
  • 原文地址:https://www.cnblogs.com/programmer-wfq/p/5924751.html
Copyright © 2011-2022 走看看