【发布时间】:2019-09-21 16:21:27
【问题描述】:
我是 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 个结果字符串。
但是,最后 2 个 printf() 仅打印未知/随机字符(可能是地址?)。有什么帮助吗?
【问题讨论】:
-
您在哪里为
host_ip[]数组元素的两个字符串分配或分配内存?你已经声明了这个数组,但仅此而已。 -
我认为通过写
char *my_conf[1]我会创建类似:my_conf = ["conf1"]。换句话说,我将创建一个指针,该指针将指向具有 1 个值的数组的开头(该值可以具有任何大小)。也许这不是发生的事情...... -
sizeof(conf)给你指针的大小,而不是它指向的大小。sizeof(*conf)会给你 char 的大小,即。 1. 必须将长度作为参数传递,或者在函数中使用strlen。 -
re2c.org/manual/manual.html 给出了一个使用 s-tags 很好地解析 IPv4 IP 的示例。