Reputation: 173
What I am trying to accomplish here is a dictionary with linked list. There is an array of node pointers. I am trying to initialize each array pointer using malloc. When I remove the for loop, it works fine.
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include "dictionary.h"
unsigned int count = 0;
unsigned int collisions = 0;
unsigned long index = 0;
#define HASHTABLE_SIZE 1999099
// Initialize struct for linked list.
typedef struct node{
char word[46];
struct node *next;
} node;
// Initialize an array of node pointers.
node *hashtable[HASHTABLE_SIZE];
for(unsigned long i = 0; i < HASHTABLE_SIZE; i++)
// Error here reads expected "=",";","asm" or __attribute__ before "<"
{
hashtable[i] = (node *)malloc(sizeof(node));
}
Upvotes: 2
Views: 287
Reputation: 500317
Since the for(unsigned long i = 0; ...
construct is only valid in C99, my guess is that you're not compiling your code as C99 (or your compiler is not C99-compliant).
An easy way to check is by moving the declaration of i
to the top of the enclosing code block.
I am assuming that what you're showing us in not the whole compilation unit, but excerpts from it. If the assumption is wrong, and the code you've shown resides outside all functions, then you need to enclose it in a function, as explained by @Keith Thompson.
Upvotes: 3
Reputation: 263237
Statements are allowed only inside functions.
Add
int main(void) {
before the for loop, and
return 0;
}
after it. Or, if main
is in another file, define some other function to contain the loop.
Upvotes: 6
Reputation: 17085
If you want to use for loops while declaring variables inside them you have to use the C99 standard. I don't know about other compilers but with gcc you'll need to pass the flag --std=c99
.
This will compile for loops like the one you have:
for(unsigned long i = 0; i < HASHTABLE_SIZE; i++)
Upvotes: 0
Reputation: 12727
It should read
node *hashtable[HASHTABLE_SIZE];
unsigned long i;
for(i = 0; i < HASHTABLE_SIZE; i++)
// Error here reads expected "=",";","asm" or __attribute__ before "<"
{
hashtable[i] = (node *)malloc(sizeof(node));
}
You cannot declare a variable inside a for()
in C, only in C++ and (as @DonFego pointed out) in C99.
Upvotes: 0