我正在尝试为指针结构变量赋值。 这就是我想要做的 -
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->概率赋值。 请给我一个解决方案。
答案 0 :(得分:2)
对我来说很好。这是我的代码
// 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
答案 1 :(得分:0)
我认为主要问题是strtok
使用\0
符号执行分隔符的就地替换:
http://pubs.opengroup.org/onlinepubs/009695399/functions/strtok.html
它被空字节覆盖,该字节终止当前标记
如果你将buf变量声明为char * buf = "5 10 0";
,则意味着buf指向只读数据部分,因此无法使用strtok,修复的简单方法是使用char buf[] = "5 10 0";