strtok_r导致“赋值从没有强制转换的整数中生成指针”

时间:2013-06-10 00:14:46

标签: c string variable-assignment strtok

我正在尝试在C中对String进行标记,并使用strtok_r将标记保存到多个变量中。据我所知,我完全按照记录使用它:

char *saveptr;

char *ticketuser = strtok_r(request, ":", &saveptr);
char *ticketservice = strtok_r(NULL, ":", &saveptr);
char *ticketkey = strtok_r(NULL, ":", &saveptr);
//And so on...

其中'request'是冒号分隔的标记字符串。当我尝试编译时,我在每个指定其中一个字符串的行上得到“赋值从整数而不是强制转换”。由于strtok_r应该返回char *,我看不出是什么问题。

编辑:这是我的所有代码:

#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

2 个答案:

答案 0 :(得分:10)

在评论中找到答案:我在文件顶部缺少#include <string.h>

编辑:我应该补充一点,除了上面提到的问题之外还有其他问题。首先,saveptr应初始化为null。其次,正如BLUEPIXY指出的那样,returncode[]是一个局部变量。用char *returncode = malloc ( . . . );

替换了它的定义

答案 1 :(得分:0)

可以使用&#34; string.h&#34;删除它。 C中的头文件