【问题标题】:copy integer to a pointer structure variable将整数复制到指针结构变量
【发布时间】:2017-05-22 19:18:27
【问题描述】:

我正在尝试为指针结构变量赋值。 这就是我想要做的-

struct node
    {
        char name[31];
        int probability[3];
        struct node *ptr;
    };
    typedef struct node NODE;

NODE *head;

   head  = (NODE *)malloc(sizeof(NODE));
   head->probability[0] = atoi(strtok (buf," -"));//Doesn't assingn
   head->probability[1] = atoi(strtok(NULL," -"));//Doesn't assingn
   head->probability[2] = atoi(strtok(NULL," -"));//Doesn't assingn

这里的“buf”是一个包含“5 10 0”格式值的字符串。但是上面的代码没有给 head->probability 赋值。 请给我一个解决方案。

【问题讨论】:

  • 应该可以。你能提供一个minimal reproducible example,
  • buf 是如何声明的?
  • 放入诊断 printfs 以检查 strtok 的返回。
  • 我已经检查过了。问题解决了。无论如何谢谢:)

标签: c pointers structure


【解决方案1】:

它对我来说很好用。这是我的代码

// FILE: test_struct.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#define NAME_LEN 31
#define PROB_LEN 3

struct node {
    char name[NAME_LEN];
    int probability[PROB_LEN];
    struct node *ptr;
};

typedef struct node NODE;

int main() 
{
   char buf[] = "5 10 0";
   NODE *head;
   int i;

   head = (NODE *)malloc(sizeof(NODE));
   assert(head);

   // add probabilities
   for (i=0; i < PROB_LEN; i++)
       head->probability[i] = atoi(strtok ((i == 0) ? buf : NULL," -"));

   // print probabilities
   for (i = 0; i < PROB_LEN; i++)
       printf("head->probability[%d] = %d\n", i, head->probability[i]);

   free(head);
   return 0;
}

编译和执行

gcc test_struct.c -o ts
./ts

打印结果

head->probability[0] = 5
head->probability[1] = 10
head->probability[2] = 0   

【讨论】:

  • 很高兴能帮到你:)
【解决方案2】:

我想主要问题是strtok 用\0 符号就地替换分隔符:

http://pubs.opengroup.org/onlinepubs/009695399/functions/strtok.html

它被一个空字节覆盖,终止当前令牌

如果将buf变量声明为char * buf = "5 10 0";,则表示buf指向只读数据段,所以不能使用strtok,简单的解决方法是使用char buf[] = "5 10 0";

【讨论】:

  • 我将 buf 声明为 char buf[100]。还是有问题。不过问题解决了。无论如何,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 2013-05-15
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多