[英]Is it applicable to pass pointer to character (after assigning string to it) to method and modify this string after without using array and why not?
I want to pass string to ac function using pointer to char and modify it and it gave me segmentation fault. 我想使用指向char的指针将字符串传递给ac函数并对其进行修改,这给了我分段错误。 I don't know why ?
我不知道为什么? Note*: I know I can pass the string to array of character will solve the problem
注意*:我知道我可以将字符串传递给字符数组来解决问题
I tried to pass it to array of character and pass to function the name of array and it works , but I need to know what the problem of passing the pointer to character. 我试图将其传递给字符数组,并传递给函数名称数组,它可以工作,但是我需要知道将指针传递给字符的问题。
void convertToLowerCase(char* str){
int i=0;
while(str[i] != '\0')
{
if(str[i]>='A'&& str[i]<='Z'){
str[i]+=32;
}
i++;
}
}
int main(void){
char *str = "AHMEDROSHDY";
convertToLowerCase(str);
}
I expect the output str to be "ahmedroshdy", but the actual output segmentation fault 我期望输出str为“ ahmedroshdy”,但实际的输出分段错误
This (you had char str*
which is a syntax error, fixed that): 这(您有
char str*
这是一个语法错误,已修复):
char *str = "AHMEDROSHDY";
is a pointer to a string literal , thus it cannot be modified, since it is stored in read-only memory. 是指向字符串文字的指针,因此不能修改,因为它存储在只读存储器中。
You modify it here str[i]+=32;
您在这里修改它
str[i]+=32;
, which is not allowed. ,这是不允许的。
Use an array instead, as @xing suggested, ie char str[] = "AHMEDROSHDY";
按照@xing的建议,改用数组,即
char str[] = "AHMEDROSHDY";
. 。
To be more precise: 更准确地说:
char *str = "AHMEDROSHDY";
'str` is a pointer to the string literal. “ str”是指向字符串文字的指针。 String literals in C are not modifacable
C中的字符串文字不可修改
in the C standard: 在C标准中:
The behavior is undefined in the following circumstances: ...
在以下情况下,行为是不确定的:...
- The program attempts to modify a string literal
程序尝试修改字符串文字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.