c - 为什么这段代码会出现指针错误?

标签 c pointers types

我收到以下行的以下错误:

randmst.c:42: warning: assignment makes integer from pointer without a cast

randmst.c:43: error: incompatible types in assignment

randmst.c:44: warning: assignment makes integer from pointer without a cast

randmst.c:50: error: invalid type argument of ‘unary *’

我的代码:

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


    //function generates a random float in [0,1]
    float rand_float();

    //all info for a vertex
    typedef struct{
        int key;
        int prev;
        float loc;
    } Vertex;

    //using the pointer
    typedef Vertex *VertexPointer;

    int main(int argc, char **argv){

        //command line arguments
        int test = atoi(argv[1]);
        int numpoints = atoi(argv[2]);
        int numtrials = atoi(argv[3]);
        int dimension = atoi(argv[4]);

        //seed the psuedo-random number generator
        srand(time(NULL));

        //declare an array for the vertices
        int nodes[numpoints];

        //create the vertices in the array
        int x;
        for(x = 0; x < numpoints; x++){
            //create the vertex
            VertexPointer v;
            v = (VertexPointer)malloc(sizeof(Vertex));
            (*v).key = 100;
            (*v).prev = NULL;
            (*v).loc = rand_float;
            nodes[x] = v;
        }

        //testing
        int y;
        for(y = 0; y < numpoints; y++){
            printf("%f \n", (*nodes[y]).loc);
        }

    }


    //generate a psuedo random float in [0,1]
    float
    rand_float(){
        return (float)rand()/(RAND_MAX);
    }

最佳答案

//declare an array for the vertices
        int nodes[numpoints];

44 nodes[x] = v;

但是 v 是 VertexPointer 类型。节点数组必须是 VertexPointer 数组

//declare an array for the vertices
VertexPointer nodes[numpoints];

这也会修复第 50 行的错误。同样在其他线路上,

42           (*v).prev = NULL;

prev 是一个 int,但是你分配了一个 NULL,它是一个 pointer。您可以将 prev 更改为 void * 或将 NULL 更改为 0

43            (*v).loc = rand_float;

rand_float 是一个函数名,它会衰减为一个指针。您可以将 loc 更改为 void * 或将 rand_float 更改为 rand_float() <- 请在此处查看区别。 rand_float 是指针,但是 rand_float() 是一个返回 float

的函数调用

关于c - 为什么这段代码会出现指针错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216257/

相关文章:

c - 需要帮助理解 C 中的特定定义指令

c - 结构指针实现方法

c - 如何阻止 waitpid 卡在某些输入上

c++ - 在函数中创建结构对象并传递其指针

c - 为什么不使用 *(a+1) 打印二维数组元素?

C++ 删除 base 或 dynamic_cast 指针?

c++ - 使用 `memcpy()` 为指针分配地址

c++ - 公共(public)基类的派生类的 TypeID

java - 告诉 Java Class<T> T 中有某个方法

Haskell 整数和 Int 类型;转换不起作用