c-链表中的所有节点都指向同一个对象



问题就在这里。。。。

char buffer[80];
char *name;
while (1) {
    fgets(buffer, 80, inf); //reads in at most 80 char from a line
        if (feof(inf)) //this checks to see if the special EOF was read
            break;     //if so, break out of while and continue with your main
        name = (char *) malloc(sizeof(char)*20);
        ....
        name = strtok(buffer, " ");//get first token up to space
        stock = newStock(name,...)
        ....
    }

我在C语言中使用通用链表。我做了一个列表实现,我已经测试过了,并且知道它可以使用字符。我正试图将股票(我创建了一个股票结构)添加到链表中,链表的每个节点都有一个股票构造,但当我读完股票后,所有节点都指向同一个结构,我不知道为什么。以下是我的代码的一些片段

list *list = malloc(sizeof(list));
newList(list, sizeof(stock_t));
while(1) {
    ...
    (read from file)
    ...
    stock_t *stock;
    stock = newStock(name, closes, opens, numshares, getPriceF, getTotalDollarAmountF,getPercentChangeF,toStringF);
    addToBack(list, stock);
}

这是newStock函数:

stock_t *newStock(char *name, float closingSharePrice, float openingSharePrice, int numberOfShares, getPrice getP, getTotalDollarAmount getTotal, getPercentChange getPercent, toString toStr) {
    stock_t *stock = malloc(sizeof(stock));
    stock->stockSymbol = name;
    stock->closingSharePrice = closingSharePrice;
    stock->openingSharePrice = openingSharePrice;
    stock->numberOfShares = numberOfShares;
    stock->getP = getP;
    stock->getTotal = getTotal;
    stock->getPercent = getPercent;
    stock->toStr = toStr;
    return stock;
}

在某种程度上,我看到了问题所在。newStock每次都返回一个新指针,但它总是存储在变量"stock"中,这是每个节点所指向的,所以它将等于newStock返回的最后一个指针。。。但我不知道该怎么办。我试着让newStock只返回一个stock_t,并添加ToBack(list,&stock),但这也没有解决问题。

任何帮助都将不胜感激!

以下是列表中的一些代码:

typedef struct node {
    void *data;
    struct node *next;
}node_t;
typedef struct {
    int length;
    int elementSize;
    node_t *head;
    node_t *tail;
} list;

void newList(list *list, int elementSize) {
    assert(elementSize > 0);
    list->length = 0;
    list->elementSize = elementSize;
   list->head = list->tail = NULL;
}
void addToBack(list *list, void *element) {
    node_t *node = malloc(sizeof(node_t));
    node->data = malloc(list->elementSize);
    node->next = NULL; //back node
    memcpy(node->data, element, list->elementSize);
    if (list->length == 0) { //if first node added
        list->head = list->tail = node;
    }
    else {
        list->tail->next = node;
        list->tail = node;
    }
    list->length++;
}

这是来自股票结构的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef float (*getPrice)(void *S);
typedef float (*getTotalDollarAmount)(void *S);
typedef float (*getPercentChange)(void *S);
typedef char *(*toString)(void *S);
typedef struct stock{
    char *stockSymbol;
    float closingSharePrice;
    float openingSharePrice;
    int numberOfShares;
    getPrice getP;
    getTotalDollarAmount getTotal;
    getPercentChange getPercent;
    toString toStr;
   }stock_t;

通用函数可能看起来有些过头了,但这是家庭作业(如果你还不能说的话),所以我们被要求专门使用它们。不过,我认为这与问题无关。

以下是这些功能的定义

float getPriceF(void *S) {
    stock_t *stock = (stock_t*)S;
    return stock->closingSharePrice;
}
float getTotalDollarAmountF(void *S) {
    stock_t *stock = (stock_t*)S;
    return ((stock->closingSharePrice) * (stock->numberOfShares));
}
float getPercentChangeF(void *S) {
    stock_t *stock = (stock_t*)S;
    return ((stock->closingSharePrice - stock->openingSharePrice)/(stock->openingSharePrice));
}
char *toStringF(void *S) {
    stock_t* stock = (stock_t*)S;
    char *name = malloc(20*sizeof(char));
    //sprintf(name, "Symbol is: %s. ", (stock->stockSymbol));
    return stock->stockSymbol;
}
void printStock(void *S) {
    char *str = toStringF(S);
    printf("%s n", str);
}

这就是我遍历列表的方式:

typedef void (*iterate)(void *); //this is in the list.h file, just putting it here to avoid confusion

void traverse(list *list, iterate iterator) {
    assert(iterator != NULL);
    node_t *current = list->head;
    while (current != NULL) {
        iterator(current->data);
        current = current->next;
    }
}

然后我打电话给

traverse(list, printStock);

我找不到你的代码有任何问题(无论如何,这会导致你的问题——有些地方你不检查malloc()的返回等等,但这些与这个问题无关)。您没有提供stock_t的定义,所以我制作了一个新的数据结构和两个新函数,否则我只是复制并粘贴您提供的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/*  Your code starts here */
typedef struct node {
    void *data;
    struct node *next;
}node_t;
typedef struct {
    int length;
    int elementSize;
    node_t *head;
    node_t *tail;
} list;

void newList(list *list, int elementSize) {
    assert(elementSize > 0);
    list->length = 0;
    list->elementSize = elementSize;
    list->head = list->tail = NULL;
}
void addToBack(list *list, void *element) {
    node_t *node = malloc(sizeof(node_t));
    node->data = malloc(list->elementSize);
    node->next = NULL; //back node
    memcpy(node->data, element, list->elementSize);
    if (list->length == 0) { //if first node added
        list->head = list->tail = node;
    }
    else {
        list->tail->next = node;
        list->tail = node;
    }
    list->length++;
}
/* Your code ends here */
/*  I made a new struct, rather than stock, since you didn't supply it  */
struct mydata {
    int num1;
    int num2;
};
/*  I use this instead of newStock(), but it works the same way  */
struct mydata * newNode(const int a, const int b) {
    struct mydata * newdata = malloc(sizeof *newdata);
    if ( newdata == NULL ) {
        fputs("Error allocating memory", stderr);
        exit(EXIT_FAILURE);
    }
    newdata->num1 = a;
    newdata->num2 = b;
    return newdata;
}
/*  I added this function to check the list is good  */
void printList(list * list) {
    struct node * node = list->head;
    int n = 1;
    while ( node ) {
        struct mydata * data = node->data;
        printf("%d: %d %dn", n++, data->num1, data->num2);
        node = node->next;
    }
}
/*  Main function  */
int main(void) {
    list *list = malloc(sizeof(list));
    newList(list, sizeof(struct mydata));
    struct mydata * data;
    data = newNode(1, 2);
    addToBack(list, data);
    data = newNode(3, 4);
    addToBack(list, data);
    data = newNode(5, 6);
    addToBack(list, data);
    printList(list);
    return 0;
}

它输出这个:

paul@MacBook:~/Documents/src$ ./list
1: 1 2
2: 3 4
3: 5 6
paul@MacBook:~/Documents/src$ 

演示您有一个3个节点的列表,所有节点都不同,以及您希望它们在哪里。

要么是代码中有其他问题,你没有显示,要么是出于某种原因,你认为每个节点都指向同一个struct,而实际上并没有。

一种可能性是您的股票结构中有一个char *数据成员。从您提供的代码中无法判断,但有可能您确实在创建不同的节点,但它们最终都指向同一个name,所以它们看起来是一样的。如果你给name分配一个指针,你应该确保它每次都是新分配的内存,而且你不仅仅是strcpy()进入同一个内存,并为每个股票struct分配相同的地址。

编辑:看来这是你的问题。此:

name = (char *) malloc(sizeof(char)*20);
....
name = strtok(buffer, " ");

应该是:

name = (char *) malloc(sizeof(char)*20);
....
strcpy(name, strtok(buffer, " "));

现在,您malloc()新内存并在name中存储对它的引用,但当您用strtok()返回的地址覆盖它时,就会丢失该引用和内存。相反,您需要将该令牌复制到新分配的内存中,如图所示。

相关内容

  • 没有找到相关文章

最新更新