如何修复将指针转换为整数?

时间:2019-03-04 05:09:31

标签: c pointers casting

我正在编写一个程序,该程序从数组中创建一个双向链接列表。到目前为止,这是代码:

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

struct Node {
    int data;
    struct Node *next;
    struct Node *previous;
}

struct Node *create_dll_from_array(int array[], int x) {
    int i;
    struct Node *newNode, *temp, *head;

    for (i=0; i<x; i++) {
        newNode = (struct Node *)malloc(sizeof(struct Node));
        newNode->data = *(array+i);
        if (i=0) {
            head = newNode;
            temp = newNode;
            newNode->next = NULL;
            newNode->previous = NULL;
        }
        else {
    ***     temp->next = (struct Node*) newNode->data;
            newNode->next = NULL;
    ***     newNode->previous = (struct Node*) temp->data;
            temp = newNode;
        }
    }
return head;
}

int main(){
    int array[5] = {11,2,7,22,4};
    struct Node* head;
    head = create_dll_from_array(array,5);
    return 0;
}

所以在带有***的行中,我得到了错误:警告:从不同大小的整数强制转换为指针 我不知道程序本身是否真正起作用,只是询问这两行以及它们为什么不起作用。谢谢!

2 个答案:

答案 0 :(得分:4)

  

如何修复将指针转换为整数?

不要将int分配给指针,然后就不再需要强制转换了。

将指针分配给指针。

// temp->next = (struct Node*) newNode->data;
temp->next = newNode;

答案 1 :(得分:0)

您可以在以下方面进行改进:

  1. 始终使用NULL初始化指针。这样可以防止指针指向无效地址。
  2. 请勿对数组大小值进行硬编码。计算。
  3. if条件下,您使用了分配=。将其更改为相等性检查==。如果您不这样做,程序将崩溃
  

问一下这两行以及它们为什么不起作用

这是因为temp->next指向类型为struct node的存储位置。您不能为其分配一个整数值(如您所做的那样)。我已在您评论的某些行下方复制了您的完整代码。

#include<stdio.h>
#include<stdlib.h>
struct Node {
    int data;
    struct Node *next;
    struct Node *previous;
};

struct Node *create_dll_from_array(int array[], int x) {
    int i;
    // struct Node *newNode, *temp, *head;
    struct Node *newNode= NULL, *temp=NULL, *head=NULL;

    for (i=0; i<x; i++) {
        newNode = (struct Node *)malloc(sizeof(struct Node));
        newNode->data = *(array+i);
        // if (i=0) {   Its wrong
        if (i==0) {
            head = newNode;
            temp = newNode;
            newNode->next = NULL;
            newNode->previous = NULL;
        }
        else {
            // temp->next = (struct Node*) newNode->data; // issue
            temp->next = (struct Node*) newNode;
            newNode->next = NULL;
            // newNode->previous = (struct Node*) temp->data; //issue
            newNode->previous = (struct Node*) temp; //issue
            temp = newNode;
        }
    }
return head;
}

int main(){
    // int array[5] = {11,2,7,22,4};
    int array[] = {11,2,7,22,4};
    struct Node* head;
    // head = create_dll_from_array(array,5);
    head = create_dll_from_array(array,sizeof(array)/sizeof(*array));
    return 0;
}

您可以做的其他优化很少是在create_dll函数内部,仅第一次遇到if条件。您可以将其移至else条件,并使else条件成为if条件

相关问题