Reputation: 1826
I have a simple function which takes an array of characters as an argument, and converts all the characters to lower case. However, I get a weird access violation error. Here's the code:
void toLower(char *rec)
{
int i=0;
while (rec[i]!='\0')
{
if (rec[i]>='A' && rec[i]<='Z')
rec[i]='a'+rec[i]-'A'; //this is where I get an error - assigning the
//the value to rec[i] is the problem
i++;
}
}
Can you tell me what's my mistake? Thanks
Upvotes: 3
Views: 1097
Reputation: 110145
In a comment you say that you pass in a literal string to the function, like this:
palindrome("In girum imus nocte et consumimur igni")
where palindrome
passes its argument to toLower
. This won't work because string literals are read-only and you are trying to modify it. Instead, you can use:
char str[] = "In girum imus nocte et consumimur igni";
palindrome(str);
Or you can have palindrome
copy its argument into an array and call toLower
on that.
Upvotes: 6
Reputation: 40730
Are you passing in (even indirectly) a string literal? If so, then it may be loaded in unwriteable memory; you'll need to make changes on a copy.
That your function prototype takes a char *
rather than a const char *
suggests that you've probably not done this, but I thought I`d throw it out.
Upvotes: 6
Reputation: 7135
Sounds like you didn't pass in a valid buffer. But don't write this yourself; use something like strlwr.
Upvotes: 1
Reputation: 106589
You're working too hard :)
#include <algorithm> //For std::transform
#include <cctype> //For std::tolower
#include <cstring> //For std::strlen
void toLower(char *rec)
{
std::transform(rec, rec + std::strlen(rec), rec, std::tolower);
}
Upvotes: 6