I'm a C noob and I'm having problems with the following code:
#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]);
}
I want to modify the host_ip array inside the split_string function and then print the 2 resulting strings in the main.
However, the 2 last printf() are only printing unknown/random characters (maybe an address?). Any help?
host_ip[]array? You've declared this array but that's all.char *my_conf[1]I would create something like:my_conf = ["conf1"]. In other words, I would be creating a pointer that would point to the beginning of an array with 1 value (this value could have any size). Maybe this is not what happens...sizeof(conf)gives you size of the pointer, not size of what it points to. Andsizeof(*conf)would give you size of char, ie. 1. You have to pass the length as parameter, or usestrlenin the function.