0

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

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

下面的代码是我迄今为止的尝试,但它没有打印出我期望的内容。结果是随机的 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;
 }
4

1 回答 1

1

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

将函数更改为

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.

于 2012-09-19T22:59:26.340 回答