2014-03-06 79 views
0

我收到以下錯誤以下行:爲什麼在這段代碼中有指針錯誤?

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); 
    } 
+0

你能指出哪些線路出現錯誤嗎? – Barmar

+1

'節點[x]'具有'int'類型,而'v'是某種類型的指針,不能'nodes [x] = v;'。 –

+0

順便說一句,你不應該在C中拋出'malloc'的結果。http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Barmar

回答

4
//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; 

prevint,但ü分配NULL其是pointer。您可以更改prevvoid *NULL0

43   (*v).loc = rand_float; 

rand_float是一個函數名,其衰減到pointer。您可以將loc更改爲void *rand_floatrand_float() < - 請參閱此處的區別。 rand_float是指針,但rand_float()是一個函數調用返回float

+0

謝謝!任何有關錯誤c.42和c.43的見解? – hannah

+0

請參閱編輯謝謝。 –

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];

1

這導致約一元*的誤差:

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

nodes[y]int,但*用於解除引用的指針。

相關問題