简体   繁体   中英

lower case string in c

i had a few line here :

#include <stdio.h>

char *tolower(char *data)
{
    char *p = data;
    while(*p)
    {
        printf("nilai p : %c\n",*p);
            if(*p >= 'A' && *p <= 'Z')
            {
                *p += ('a' - 'A');
            }
        p++;
    }
    return p;

}

int main()
{

    char *a = "HajAR BleH";
    char *b = tolower(a);

    printf("nilai b : %s\n",b);
    printf("nilai a - A : %d\n",'a' - 'A');
return 0;
}

next, compiled, running on gdb, and segmentation traced

xxx@aaa:/tmp$ gcc -o aa aa.c --debug
xxx@aaa:/tmp$ gdb -q aa
Reading symbols from /tmp/aa...done.
(gdb) r
Starting program: /tmp/aa 
nilai p : H

Program received signal SIGSEGV, Segmentation fault.
0x0804841e in tolower (data=0x804855e "HajAR BleH") at aa.c:11
11                  *p += ('a' - 'A');
(gdb) 

question

1. i think *p += ('a' - 'A'); will equal as 'H' += ('a' - 'A') and equal with 72 += 32 but, accidentally segmentation fault, how come it could be ?

2. why need to add ('a' - 'A') to make char / byte get lower ?

thats all for now, thank in advance

You are trying to modify a string literal. Change:

char *a = "HajAR BleH";

to:

char a[] = "HajAR BleH";

Also, there already is a standard library function called tolower(), which you should in fact be using in your code. Call your own function something else.

The most likely cause of the SEGV is that the compiler has placed a in read-only memory, as it is allowed to do with string literals.

Try changing a 's definition to:

char a[] = "HajAR BleH";

As a matter of style, there already exists a standard function called tolower , which does something different (convert one character to lowercase). With this in mind, I'd suggest:

  1. giving your function a different name to avoid confusion;
  2. using tolower in your implementation to convert one character to lowercase.

The reason for the seg-fault is you are trying to modify a string literal which is resides in read only memory leading to undefined behavior.

Try changing

char *a = "HajAR BleH";

to

char a[] = "HajAR BleH";

As well as the problem with the read-only memory, you need to return data rather than p . By the time your loop has finished, p points to the null-terminator.

1: Essentially your code is correct, however you're trying to modify a constant string ( char *a should reda const char *a ). You'll have to create another character array you'll be able to modify.

2: ('a' - 'A') calculates the "difference" in the ascii values between lower case characters and upper case characters (32).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM