将整数复制到指针结构变量

标签 c pointers structure

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

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 赋值。 请给我一个解决方案。

最佳答案

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

// 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   

关于将整数复制到指针结构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120577/

相关文章:

c - 为什么字符串数组中的 "Hello"的大小为 4?

structure - 在 C 中按姓氏按字母顺序排列结构化列表

c - 算术和强制转换指针和结构

c++ - 在 while 循环中打印零

c - 在执行 strcmp 之前检查第一个字符有用吗?

c - char* 究竟定义了什么?如果它定义了一个字符串数组,我如何输出单个元素?

c - 在 C 中,结构名称何时必须包含在结构初始化和定义中?

c++ - 在 Linux 上跟踪 libc 和系统调用函数调用?

c - 关于 CS50 pset2 vigenere

C++ 从 void* 中恢复指向未知关联容器的元素