I'm getting an error (unhandled exception writing address so and so) trying to modify a string. It gets weirder though. Let me show what i've got:
--Main.c--
#include "stdafx.h"
#include "commands.h"
int main(int argc, char* argv[])
{
char word[256];
int id;
strcpy(word, "move");
strToUpper(word);
printf("%s", word);
id = getCommandId(word);
if(id == -1)
perror("Error");
else if(id == 0)
printf("No such command.");
else
printf("ID: %d\n", getCommandId("move"));
getchar();
return 0;
}
--commands.h--
#pragma once
#define COMMAND_MOVE 1
#define COMMAND_TAKE 2
#define COMMAND_LOOK 3
int getCommandId(char *word);
void strToUpper(char *str);
And --commands.c--
#include "stdafx.h"
#include "commands.h"
void strToUpper(char *str)
{
int i = 0;
while(str[i] != '\0')
{
str[i++] &= 0xDF; //reset bit 5
}
}
int getCommandId(char *word)
{
FILE *fp;
char buf[256];
char *tok;
int i = 0;
fp = fopen("commands.dat", "r");
if(fp == NULL)
return -1;
strToUpper(word);
while(++i)
{
if(fgets(buf, 255, fp) == NULL)
break;
tok = strtok(buf, " ");
while(tok != NULL)
{
if(strcmp(tok, word) == 0)
return i;
tok = strtok(NULL, " ");
}
}
return 0;
}
Nothing real exciting happens with the call to strToUpper in main, other than the string being capitalized. Then getCommandId is called, and therefore strToUpper is too, with the same pointer word
as before. Only this time, I get the nasty error described at the top of my post. Thoughts?