Error passing C array as char* function parameter
I'm trying to make a simple code in c language (Stupid question, but I'm learning), I dont understand that this code gives me an error ... I must be doing wrong, I can not know that I have to change...sorry for my English ... thanks in advance to all
#include <stdio.h>
#include <ctype.h>
char* to_up(char* str_);
int main()
{
char any_phrase[] = "This is a phrase";
printf("%s\n", to_up(any_phrase));
printf("%s\n", to_up("this is another phrase"));
return 0;
}
char* to_up(char* str_)
{
int i;
for (i=0; str_[i]; i++)
str开发者_StackOverflow中文版_[i] = toupper(str_[i]);
return str_;
}
The reason for the error is that when you pass the string as "this is another phrase" on its own, as in not contained in a variable, the string is what's known as a string literal. What this means, among other things, is that the string is constant: you simply are not allowed to modify.
To solve your problem you'd have to store the string in a variable so it is allowed to be modified by your to_up() function call since it modifies the contents of the string.
A string literal is usually in read-only memory. As far as the standard is concerned, trying to modify it will result in undefined behaviour regardless of where it is in memory. There have been many questions asked about this problem already.
In this call
printf("%s\n", to_up("this is another phrase"));
You are trying to modify a string literal.
The code compiles OK for me, but gives a bus error (core dump) at runtime.
The trouble is that a string literal can be stored in read-only memory, so you can't modify the literal string as your code does. With enough compiler warnings enabled, your compiler will warn you (GCC requires -Wwrite-strings
- at least, in GCC 4.4 and above).
精彩评论