警告TokenList类型强制转换

时间:2014-04-10 08:43:41

标签: c struct casting token compiler-warnings

我有这个:

struct cella {
    char *token;
    struct cella *next;
};
typedef struct cella *ListaToken;

ListaToken tokenize(char *s) {
    ListaToken l;
    int i;
    while (s[i]){
        l = (ListaToken)malloc(sizeof(ListaToken));
        l->next = s[i];
        i++;
    }
    l->next = NULL;
    return l;
}

在“l-> next = s [i];”中我收到警告:赋值从整数中生成指针而没有强制转换[默认启用]。 我试图改变它很多次但是我有一些问题,我在C中不太好。我应该怎么改变它? 感谢。

编辑:我想要这样的东西来构建反向波兰表示法计算器:

tokenize(“12 17 + 4 3 - /”)=“12” - > “17” - > “+” - > “4” - > “3” - > “ - ” - > “/” - > NULL

tokenize(“12 17 + 4 - /”)=“12” - > “17” - > “+” - > “4” - > “ - ” - > “/” - > NULL

这是该计划的第一部分。

1 个答案:

答案 0 :(得分:0)

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

typedef struct cella {
    char *token;
    struct cella *next;
} *ListaToken;

ListaToken tokenize(const char *s) {
    ListaToken top = NULL, current, l;
    char *p, *tmps = strdup(s);

    for(p=strtok(tmps, " ");p;p=strtok(NULL, " ")){
        l = malloc(sizeof(*l));
        l->token = strdup(p);
        l->next = NULL;
        if(top == NULL){
            current = top = l;
        } else {
            current->next = l;
            current = l;
        }
    }
    free(tmps);
    return top;
}

void print(ListaToken l){
    while(l){
        printf("\"%s\" -> ", l->token);
        l = l->next;
    }
    printf("NULL\n");
}
int main(){
    ListaToken list1, list2;
    list1 = tokenize("12 17 + 4 3 - /");
    print(list1);
    list2 = tokenize("12 17 + 4 - /");
    print(list2);

    return 0;
}

char *mystrdup(const char *s){
    char *dup = malloc(strlen(s) + 1);
    return strcpy(dup, s);
}

char *mystrtok_r(char *str, const char *delims, char **store){
    char *p, *wk;
    if(str != NULL){
        *store = str;
    }
    if(*store == NULL) return NULL;
    *store += strspn(*store, delims);//skip delimiter
    if(**store == '\0') return NULL;
    p=strpbrk(wk=*store, delims);
    if(p != NULL){
        *p='\0';
        *store = p + 1;
    } else {
        *store = NULL;
    }
    return wk;
}

char *mystrtok(char *str, const char *delimis){
    static char *store;
    return mystrtok_r(str, delimis, &store);
}

ListaToken tokenize(const char *s) {
    ListaToken top = NULL, current, l;
    const char *p = s, token[16];
    int len=0;
    while(1==sscanf(p, "%15s%n", token, &len)){
        l = malloc(sizeof(*l));
        l->token = malloc(len + 1);
        strcpy(l->token, token);
        p += len;
        l->next = NULL;
        if(top == NULL){
            current = top = l;
        } else {
            current->next = l;
            current = l;
        }
    }
    return top;
}