首页 > 解决方案 > 修改函数中的数组后输出错误(在 C 中)

问题描述

我是 C 菜鸟,我在使用以下代码时遇到问题:

#include <stdio.h>
#include <string.h>
#include <unistd.h>

void split_string(char *conf, char *host_ip[]){

    long unsigned int conf_len = sizeof(conf);
    char line[50];
    strcpy(line, conf);

    int i = 0;

    char* token; 
    char* rest = line; 

    while ((token = strtok_r(rest, "_", &rest))){
        host_ip[i] = token;
        printf("-----------\n");
        printf("token: %s\n", token);
        i=i+1;
    }
}

int main(){ 

    char *my_conf[1];

    my_conf[0] = "conf01_192.168.10.1";

    char *host_ip[2];
    split_string(my_conf[0], host_ip);

    printf("%s\n",host_ip[0]);
    printf("%s\n",host_ip[1]);
}

我想修改 split_string 函数中的 host_ip 数组,然后在 main.xml 中打印 2 个结果字符串。

但是,最后两个 printf() 仅打印未知/随机字符(可能是地址?)。有什么帮助吗?

标签: cfunction

解决方案


有2个问题:

首先,您要返回指向局部变量的指针。strdup您可以通过在调用者中调用字符串并释放来避免这种情况。

第二:

在第一次调用 时strtok_r()str应该指向要解析的字符串,并且saveptr忽略 的值。在随后的调用中,str应该是NULL,并且saveptr应该自上次调用以来保持不变。

你必须NULL在循环中的第一次迭代之后的第一个参数。没有地方说可以对两个参数使用相同的指针。这是因为strtok_r几乎是 Braindead 的直接替代品strtok,只需一个额外的参数,因此您甚至可以用宏包装它......

因此我们得到

char *start = rest;
while ((token = strtok_r(start, "_", &rest))){
    host_ip[i] = strdup(token);
    printf("-----------\n");
    printf("token: %s\n", token);
    i++;
    start = NULL;  
}

在来电者中:

free(host_ip[0]);
free(host_ip[1]);

推荐阅读