The problems is the line myArray[name] = word;
you're taking an array index from your input line and then setting the character at that position to low bits of the address of your word... I doubt that's actually what you want to do.
There's some other problems with your code, you're leaking the memory from the line word = (char *) malloc(16);
because strtok returns a pointer into the string you initially pass it. You don't actually need to malloc anything for the code as written in the question, so you could have:
char myArray[3000];
char line[100];
char *word = NULL;
word
needs to be a pointer since it's holding the result of strtok()
You clearly don't understand pointers, you need to review that before you can understand why your code isn't working the way you expect.
If you say what your code is actually meant to be doing I can give you some hints on how to fix it, but at the moment I can't quite tell what the intended result is.
EDIT: Did you intend to read in your numbers in hexadecimal? The last argument to strtol()
is the base to be used for conversion... you could also just use atoi()
so your loop could look like:
char myArray[3000];
char line[100];
char *word = NULL;
while(fgets(line, 100, file)) {
printf("%s\n", line);
word = strtok(line, " :");
if(word == NULL) continue;
name = atoi(word); /* only if you didn't actually want hexadecimal */
word = strtok(NULL, " \n");
if(word == NULL) continue;
if(name > 0 && name < 3000) { /* as I said in a comment below */
strncpy(myArray + name, word, 3000 - name);
}
}