cStrings

I get thi error! Unhandled exception at 0x0109489B in estudiar.exe: 0xC0000005: Access violation writing location 0x0109DC74. I have no idea why.

#include <iostream>
#include <cstring>

void capitalize(char *);

int main()
{
char *nom = "hello. how are you.";
capitalize(nom);
std::cout << nom << std::endl;

system("pause");
return 0;
};

void capitalize(char *cStr)
{
cStr[0] = toupper(cStr[0]);
while(*cStr != '\0')
{
if(*cStr == '.')
{
while(!isalpha(*cStr))
cStr++;
*cStr = toupper(*cStr);
}
cStr++;
}
}
Last edited on
-
Last edited on
nom points to a string literal. string literals are read only. You cannot modify them. Doing so results in undefined behavior and that is what you're experiencing.

You also have other logic errors in capitalize that make it likely you will go beyond the end of whatever string is fed to it.

Here's a working version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstring>

void capitalize(char *);

int main()
{
    // allocate storage for a string and copy the literal to it.
    char nom[] = "hello. how are you.";

    capitalize(nom);
    std::cout << nom << std::endl;

    system("pause");
    return 0;
};

void capitalize(char *cStr)
{
    bool should_capitalize = true;

    while (*cStr)
    {
        if (should_capitalize && isalpha(*cStr))
        {
            *cStr = toupper(*cStr);
            should_capitalize = false;
        }
        else if (*cStr == '.')
            should_capitalize = true;

        ++cStr;
    }
}

thanks. Had no idea char * was not modifiable. Also thanks for fixing
capitalize
char * is a pointer. It is all a matter of what it points to. Constants are read-only, so trying to modify them can cause issues, as you have seen. If the area of memory that the point looks at is read-write, then this issue should not happen.
Topic archived. No new replies allowed.