我正在尝试为指针结构变量赋值。 这就是我想要做的 -
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/