在main中调用函数,使用strtok分隔字符串(指针有问题)

时间:2012-09-19 22:49:08

标签: c string pointers strtok

我正在用C编写一个程序,用户输入的字符串(电话联系信息)没有空格,但是姓氏,名字等信息用逗号分隔。

我要做的是编写一个函数,其中逗号之间的字符串字段成为一个标记(使用strtok_r函数)并分配给字符串数组并在程序结束时打印每个标记。 / p>

以下代码是我到目前为止的尝试,但它没有打印出我期望的内容。结果是随机的ASCII字符,我猜是因为我的指针有多糟糕。任何帮助表示赞赏。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void commaCut(char *input, char *command, char *last, char *first, char *nick, char *detail, char *phone);

int main()
{
char *str, *token, *command;
char *last, *first, *nick, *detail, *phone, *saveptr;

char input[100];
int commaCount = 0;
int j;
str = fgets(input,100,stdin);
commaCut(str, command, last, first, nick, detail, phone);
printf("%s %s %s %s %s %s\n",command,last,first,nick,detail,phone);
exit(0);
}

void commaCut(char *input, char *command, char *last, char *first, char *nick, char *detail, char *phone)
{
  char *token, *saveptr;
  int j;
  int commaCount = 0;
  for (j = 0; ; j++, commaCount++, input = NULL)
  {
    token = strtok_r(input, ",", &saveptr);
    if (token == NULL)
      break;
    if (commaCount == 0)
      command = token;
    if (commaCount == 1)
      last = token;
    if (commaCount == 2)
      first = token;
    if (commaCount == 3)
      nick = token;
    if (commaCount == 4)
      detail = token;
    if (commaCount == 5)
      phone = token;
 }

1 个答案:

答案 0 :(得分:1)

问题是在first函数中修改的指针commaCut等是main中指针的副本,所以指针在main保持不变且未初始化,并指向任意内存位置。您需要传递这些指针的地址以更改main指针的值。

将功能更改为

void commaCut(char *input, char **command, char **last, char **first, char **nick, char **detail, char **phone)
{
  char *token, *saveptr;
  int j;
  int commaCount = 0;
  for (j = 0; ; j++, commaCount++, input = NULL)
  {
    token = strtok_r(input, ",", &saveptr);
    if (token == NULL)
      break;
    if (commaCount == 0)
      *command = token;
    if (commaCount == 1)
      *last = token;
    if (commaCount == 2)
      *first = token;
    if (commaCount == 3)
      *nick = token;
    if (commaCount == 4)
      *detail = token;
    if (commaCount == 5)
      *phone = token;
 }

并将其命名为

commaCut(str, &command, &last, &first, &nick, &detail, &phone);
main中的