-2

So my program runs the numElements method but than crashes, am I declaring my variables wrong or is my pointer variable wrong?

Header.h

typedef struct Node {
int number;
struct Node *pNext;
}Node;

Other.h

void LinkedList(Node *pNode){

int i,j,c,numElem;
time_t t;
srand((unsigned) time(&t));
numElem = numElements();
pNode[numElem];

for(i = 0; i < numElem; i++){

    pNode[i].number = (rand() % (MAX - MIN)) + MIN;
    //c = (rand() % (MAX - MIN)) + MIN;
    printf("P is %d\n",pNode[i].number);
    printf("C = %d",c);

   }
}

Main.c

Node *pNode;
LinkedList(pNode);
EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40
Cmi
  • 479
  • 2
  • 5
  • 12

2 Answers2

2

I needed this pNode = malloc(numElem * sizeof(Node));

Cmi
  • 479
  • 2
  • 5
  • 12
  • 2
    Good for you figuring this out for yourself, but do you realize that you have created an array, not a linked list? (Maybe you _mean_ to make an array of linked list heads?) – zwol Oct 25 '17 at 17:24
  • @zwol I am making a linked list but am starting slow though – Cmi Oct 25 '17 at 17:26
  • @zwol by the way is it better to use realloc? – Cmi Oct 25 '17 at 17:50
  • realloc is for when you already have a chunk of memory allocated (by malloc) and you need to change how big it is. – zwol Oct 25 '17 at 18:25
-1

You need to allocate memory for pNode, for your case (C language) it could be,

pNode = malloc( numElem * sizeof(Node) );

The cast is not required for strict C, but for C++ it is.

asam
  • 359
  • 3
  • 12
  • 1
    [Don't cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – zwol Oct 25 '17 at 17:23
  • zwol, that depends on the compiler. so your classification is wrong! if, for example, it is necessary to compile with C++ also, it is requested to use the cast. I add C++ to my answer! – asam Oct 25 '17 at 17:26
  • No, it doesn't depend on the compiler. – zwol Oct 25 '17 at 17:27
  • The question is about C only. Casting the result of malloc is an actively bad practice in C and should never be encouraged. Only when someone specifically requires code that can be compiled as both C and C++ should you include that cast. – zwol Oct 25 '17 at 17:35
  • No, it is not. The question is about C only. – zwol Oct 26 '17 at 20:57