So I have a program that makes char* stuff lowercase. It does it by iterating through and manipulating the ascii. Now I know there’s probably some library for this in c++, but that’s not the point – I’m a student trying to get a grasp on char*s and stuff :).
Here’s my code:
#include <iostream> using namespace std; char* tolower(char* src); int main (int argc, char * const argv[]) { char* hello = 'Hello, World!\n'; cout << tolower(hello); return 0; } char* tolower(char* src) { int ascii; for (int n = 0; n <= strlen(src); n++) { ascii = int(src[n]); if (ascii >= 65 && ascii <= 90) { src[n] = char(ascii+32); } } return src; }
( this is not for an assignment 😉 )
It builds fine, but when I run it it I get a ‘The Debugger has exited due to signal 10’ and Xcode points me to the line: ‘src[n] = char(ascii+32);’
Thanks!
Mark
Yowsers!
Your ‘Hello World!’ string is what is called a string literal, this means its memory is part of the program and cannot be written to.
You are performing what is called an ‘in-place’ transform, e.g. instead of writing out the lowercase version to a new buffer you are writing to the original destination. Because the destination is a literal and cannot be written to you are getting a crash.
Try this;
Also in your for loop, you should use <, not <=. strlen returns the length of a string minus its null terminator, and array indices are zero-based.