为什么这段代码中有指针错误?

时间:2014-03-06 05:59:00

标签: 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);
    }

3 个答案:

答案 0 :(得分:4)

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

44 nodes[x] = v;

v的类型为VertexPointer。 nodes数组必须是VertexPointer

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

这也将修复第50行的错误。另外,在其他方面,

42           (*v).prev = NULL;

prevint,但您指定的NULLpointer。您可以将prev更改为void *NULL更改为0

43            (*v).loc = rand_float;

rand_float是一个函数名称,它会衰减为pointer。您可以将loc更改为void *rand_float更改为rand_float()&lt; - 请参阅此处的差异。 rand_float是指针,但rand_float()是函数调用,返回float

答案 1 :(得分:1)

这导致关于一元*:

的错误
        printf("%f \n", (*nodes[y]).loc);

nodes[y]int,但*用于取消引用指针。

答案 2 :(得分:0)

如果没有明确的类型转换,就不能将整数赋给指针,反之亦然。

所有错误陈述均为:

(*v).prev = NULL;      // 'prev' is 'int', 'NULL' is 'void*' type pointer
(*v).loc = rand_float; // 'loc' is 'float', 'rand_float' is 'float*' type pointer
nodes[x] = v;          // 'nodes[x]' is 'int', 'v' is 'struct Vertex *' type pointer

(*nodes[y]).loc        // 'nodes[y]' is already an integer and you are dereferencing it

要纠正这些错误,请将指定指针的变量声明为指向正确类型的指针。

示例:loc应声明为float (*loc)();int nodes[numpoints]应声明为VertexPointer nodes[numpoints];