我试图给指针结构变量赋值。
这就是我要做的-
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”是一个字符串,包含“510”格式的值。但上面的代码并没有给head赋值->概率。
请给我一个解决办法。
最佳答案
对我来说很好。这是我的密码
// 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