why does passing C string into function as char* cause runtime error (but passing C string defined as char[] is ok)?
I have a simple C program as follows:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void convertToUpperCase(char* sPtr);
int main(int argc, char** argv) {
char myString[] = "cHaRacTerS aND $32.95";
char* anotherString = "cHaRacTerS aND $32.95";
convertToUpperCase(myString); // THIS IS OK!
convertToUpperCase(anotherString); // THIS CAUSES RUNTIME ERROR
// (ie. build success but run fail)!
return (EXIT_SUCCESS);
}
void convertToUpperCase(char* sPtr) {
while (*sPtr != '\0') { // current character is not null (ie. end of string).
*sPtr = toupper(*sPtr); // turns valid characters into upper case
++sPtr; // point to next character within the string.
}
}
It seems like passing anotherString
into the function that expects a char*
is the problem. From my understanding, both myString
and anotherString
are char*
in C.
It seems to me the problem is how they are defined. But I can't figure out why the way they are defined matters in this situation.
Thanks in advance :)
from Recent Questions - Stack Overflow https://ift.tt/3rx1dkg
https://ift.tt/eA8V8J
Comments
Post a Comment