strtok_r causing "assignment makes pointer from integer without a cast" - c

I'm attempting to tokenize a String in C and save the tokens into multiple variables using strtok_r. As far as I can tell, I'm using it exactly as documented:
char *saveptr;
char *ticketuser = strtok_r(request, ":", &saveptr);
char *ticketservice = strtok_r(NULL, ":", &saveptr);
char *ticketkey = strtok_r(NULL, ":", &saveptr);
//And so on...
Where 'request' is a String of colon-delimited tokens. When I try to compile, I get "assignment makes pointer from integer without a cast" on each line where I assign one of the Strings. Since strtok_r is supposed to return a char*, I can't see what the issue is.
EDIT: Here's ALL my code:
#include <stdio.h>
char *add( char *request ) {
char *name = "add";
char *secret = "secret1";
char *failcode = "0:add:0";
char returncode[80];
char *saveptr;
char *username = strtok_r(request, ":", &saveptr);
char *servicename = strtok_r(NULL, ":", &saveptr);
int parameter1 = atoi(strtok_r(NULL, ":", &saveptr));
int parameter2 = atoi(strtok_r(NULL, ":", &saveptr));
int ticketlead1 = atoi(strtok_r(NULL, ":", &saveptr));
char *ticketuser = strtok_r(NULL, ":", &saveptr);
char *ticketservice = strtok_r(NULL, ":", &saveptr);
char *ticketkey = strtok_r(NULL, ":", &saveptr);
//Catch any issues with the request
if (strcmp(username,ticketuser) != 0){
printf("username did not match ticket username\n");
return failcode;
}//if
else if (strcmp(servicename,ticketservice) != 0){
printf("service name did not match ticket service name\n");
return failcode;
}//else if
else if (strcmp(secret,ticketkey) != 0){
printf("secret key did not match ticket secret key\n");
return failcode;
}//else if
//request was good, return value
else{
int val = parameter1 + parameter2;
sprintf(returncode, "1:add:%d", val);
return returncode;
}//else
}//add
int main( int argc, char **argv ) {
char *returned;
char *req = "user:serv:5:8:1:user:serv:secret1";
returned = add(req);
printf(returned);
printf("\n");
return 1;
}//main

Answer was found in comments: I was missing #include <string.h> at the top of the file.
EDIT: I should add that there were other issues besides the one mentioned above. Firstly, saveptr should be initialized to null. Secondly, as BLUEPIXY pointed out, returncode[] was a local variable. Replaced its definition with char *returncode = malloc ( . . . );

This can be removed by using "string.h" header file in C

Related

Cant get C program and strsep() and getenv() to all work together

I had this working before, but I was using pointers. getenv() keeps crashing so I copied the results using sprintf(). Now I want to deliminate with : and print only the first occurrence. Please help!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(void) {
char buf[999];
const char *token;
// HTTP_PROXY == 8.8.8.8:8888, end result should print 8.8.8.8
sprintf(buf, "%s", getenv("HTTP_PROXY"));
*token = strsep(&buf, ":");
printf("New result: %s\n", token);
}
Since strsep wants a pointer to pointer, you must pass a pointer to pointer, not a pointer to array. This is not the same thing; make a pointer, and assign it buf. Pass a pointer to that new pointer to strsep to fix the first problem.
The second problem is that since strsep returns a pointer, you need to assign it to token, not to *token:
char buf[999];
const char *token;
// HTTP_PROXY == 8.8.8.8:8888, end result should print 8.8.8.8
sprintf(buf, "%s", getenv("HTTP_PROXY"));
char *ptr = buf; // Since ptr, is a pointer...
token = strsep(&ptr, ":"); // ...you can pass a pointer to pointer
printf("New result: %s\n", token);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char const *http_proxy = getenv("HTTP_PROXY");
if (http_proxy == NULL) {
fprintf(stderr, "HTTP_PROXY not set: default 8.8.8.8:8888");
http_proxy = "8.8.8.8:8888";
}
char *cpy = strdup(http_proxy);
char *token = strtok(cpy, ":");
if (token == NULL) {
fprintf(stderr, "wrong format");
return 1;
}
do {
printf("Token: %s\n", token);
} while ((token = strtok(NULL, ":")) != NULL);
free(cpy);
}

break a string into 'first' and 'second'

I have read through countless strtok posts, even copied some directly in their entirety into a new int main, but I can't figure out how to create the functions get_first and get_second.
get_first("This is a sentence."); //returns "This"
get_rest("This is a sentence."); //returns "is"
This is what I have so far, I have had nothing but trouble with strtok, but I don't know what else to use.
#include <stdio.h>
#include <string.h>
char * get_first(char * string) {
string = strtok(string, " ");
return string;
}
char * get_second(char * string) {
string = strtok(string, " ");
string = strtok(NULL, " ");
return string;
}
int main(int argc, char * argv[]) {
char * test_string = "This is a sentence.";
char * first = get_first(test_string);
char * second = get_second(test_string);
printf("%s\n", first);
printf("%s\n", second);
}
Getting no faults compiling with gcc -g -Wall, but it always seg faults. I think I have tried every permutation of char c[] and char * c there is.
strtok changes the string. (but String literals are not allowed to change.)
So create a copy.
Do the following:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * get_first(const char *string){
char *clone = strdup(string);//create copy, strdup is non standard. malloc and copy.
char *token = strtok(clone, " ");
if(token)
token = strdup(token);
free(clone);
return token;
}
char * get_second(const char *string) {
char *clone = strdup(string);
char *token = strtok(clone, " ");
if(token && (token = strtok(NULL, " ")))
token = strdup(token);
free(clone);
return token;
}
int main(void) {
char * test_string = "This is a sentence.";
char * first = get_first(test_string);
char * second = get_second(test_string);
printf("%s\n", first);
printf("%s\n", second);
free(first);
free(second);
}

How to pass a character string to a function in C

I am trying to process a character string in order to change something in a file. I read from a file a character string which contains a command and an argument, separated by a space character. I separated this array in tokens.
Now I want to pass the second token, which is the argument to a function. My problem is that when I run my program, the screen freezes and nothing happens. Here is my separating way and the call to the function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void create_file(char *argument)
{
//some code goes here
}
int main()
{
int i = -1;
char *token[5];
char command[20];
const char delim[1] = " ";
FILE *fin;
fin = fopen("mbr.op", "r");
while(fscanf(fin, "%[^\n]", command) == 1)
{
i = -1;
token[++i] = strtok(command, delim);
while(token[i] != NULL)
token[++i] = strtok(NULL, delim);
if(strcmp(token[0], "CREATE_FILE") == 0)
create_file(token[1]);
}
fclose(fin);
return 0;
}
You have a few errors, first command[20] is an uninitialised string and that will cause undefined behaviour. Second, you failed to check the first arg as well as the second, so I added a test where commented. Also, the strings are not long enough so I removed the length. Lastly I test for a NULL pointer passed to the function.
Edit code was added to the question to show that command[20] was initialised, but it is still too short to take the command and a reasonable file name (thanks to #ameyCU).
#include <stdio.h>
#include <string.h>
void create_file(char *argument)
{
if(argument == NULL)
printf("NULL pointer\n");
else
printf("Arg: %s\n", argument);
}
int main(void)
{
int i = -1;
char *token[5];
char command[] = "CREATE_FILE myfile.txt";
const char delim[] = " ";
token[++i] = strtok(command, delim);
while(token[i] != NULL)
token[++i] = strtok(NULL, delim);
if(token[0] != NULL && strcmp(token[0], "CREATE_FILE") == 0) // added test
create_file(token[1]);
return 0;
}
Program output
Arg: myfile.txt
The first error is present in array definition:
const char delim[1] = " ";
In C "" is a string - an array of characters delimited by '\0'. This means that what stands to the right of "=" is a string of two chars:
// ' ' + '\0'
//0x20 0x00
Therefore this should be an array of two chars:
const char delim[2] = " ";
or
const char delim[] = " ";

issue to extract token from sub token using strtok() function in c

Have written following code in c
#include "stdio.h"
#include "string.h"
int main()
{
char str[] = "gatway=10.253.1.0,netmask=255.255.0.0,subnet=10.253.0.0,dns=10.253.0.203";
char name[100],value[100];
char *token1,*token2;
char *commasp = ", ";
char *equ="=";
token1 = strtok(str,commasp);
while(token1 != NULL)
{
token2 = strtok(token1,equ);
sprintf(name,"%s",token2);
token2 = strtok(NULL,commasp);
sprintf(value,"%s",token2);
printf("Name:%s Value:%s\n",name,value);
token1 = strtok(NULL,commasp);
}
return 0;
}
My problem is i got only one printf like Name:gatway Value:10.253.1.0. i know last strtok() in while loop followed by previous strok() which turns to null so token1 get null value and break the loop. Have think solution for it to not use strtok() in while loop for sub token (getting name and value) and use other method to extract name and value but it seems to lengthy code(using for or while loop for character match).So any one have batter solution to packup code in single loop.
You could use strtok_r instead of strtok.
char *key_value;
char *key_value_s;
key_value = strtok_r(str, ",", &key_value_s);
while (key_value) {
char *key, *value, *s;
key = strtok_r(key_value, "=", &s);
value = strtok_r(NULL, "=", &s);
printf("%s equals %s\n", key, value);
key_value = strtok_r(NULL, ",", &key_value_s);
}
gatway equals 10.253.1.0
netmask equals 255.255.0.0
subnet equals 10.253.0.0
dns equals 10.253.0.203
Frankly though I think it would be easier to just look for , and when you find one look for = backwards.
You can do this in two steps, first parse the main string:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "gatway=10.253.1.0,netmask=255.255.0.0,subnet=10.253.0.0,dns=10.253.0.203";
char name[100],value[100];
char *commasp = ", ";
char *ptr[256], **t = ptr, *s = str;
*t = strtok(str, commasp);
while (*t) {
t++;
*t = strtok(0, commasp);
}
for (t = ptr; *t; t++) {
printf("%s\n", *t);
// now do strtok for '=' ...
}
return 0;
}
Then parse individual pairs as before.
The above results in:
gatway=10.253.1.0
netmask=255.255.0.0
subnet=10.253.0.0
dns=10.253.0.203

insert strtok results into char* (increased dynamic)

I'm loosing my mind.
I want to split string (char* text) with spaces and insert the string results into array and return this array.
I have the following method in C
char *read_command(char *text)
{
int index=0;
char *res=NULL;
char *command= (char*)malloc(strlen(text)+1);
strcpy(command, text);
char *tok = strtok(command, " ");
while(tok!=NULL && index ==0)
{
res = (char*)realloc(res, sizeof(char)*(index+1));
char *dup = (char*)malloc(strlen(tok)+1);
strcpy(dup, tok);
res[index++] = dup; //Error here
tok = strtok(NULL, " ");
}
res[index++]='\0';
return res;
}
from main method
char *input="read A B C";
char *command = read_command(input);
Thank you
You are using a wrong type to calculate the size in this call:
res = realloc(res, sizeof(char)*(index+1));
You need to use char*, not char, with sizeof, like this:
res = realloc(res, sizeof(char*)*(index+1));
Since your code returns a pointer to C strings (represented as char*) the return type should be char**.
You need to remove the index == 0 condition from the while loop, otherwise it wouldn't go past the initial iteration.
This assignment
res[index++]='\0';
should be
res[index++]=NULL;
You also need to call free(command) before returning the results to the caller. Finally, you should not cast results of malloc in C.
Here is your code after the fixes above:
char **read_command(char *text) {
int index=0;
char **res=NULL;
char *command= malloc(strlen(text)+1);
strcpy(command, text);
char *tok = strtok(command, " ");
while(tok!=NULL) {
res = realloc(res, sizeof(char*)*(index+1));
char *dup = malloc(strlen(tok)+1);
strcpy(dup, tok);
res[index++] = dup;
tok = strtok(NULL, " ");
}
// Need space to store the "terminating" NULL
// Thanks, BLUEPIXY, for pointing this out.
res = realloc(res, sizeof(char*)*(index+1));
res[index]=NULL;
free(command);
return res;
}
Demo on ideone.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **read_command(const char *text){
int index=0;
char **res=NULL;
char *command= malloc(strlen(text)+1);
strcpy(command, text+strspn(text, " \t\n"));//strspn for skip space from top
char *tok = strtok(command, " ");
res = realloc(res, sizeof(char*)*(index+1));
while(tok!=NULL){
res[index++] = tok;
res = realloc(res, sizeof(char*)*(index+1));
tok = strtok(NULL, " ");
}
res[index++]=NULL;
return res;
}
int main(void){
char *input="read A B C";
char **command = read_command(input);
int i;
for(i=0;command[i]!=NULL;++i){
printf("s[%d]=%s\n", i, command[i]);
}
free(command[0]);//for free command of read_command
free(command);//for free res of read_command,,
return 0;
}

Resources