This question already has answers here:
Why is this string reversal C code causing a segmentation fault? [duplicate]
(8个答案)
2年前关闭。
为什么我的代码在指定的行中生成SIGSEGV?我想将字符串的第一个字符更改为“ k”(小写)
(8个答案)
2年前关闭。
为什么我的代码在指定的行中生成SIGSEGV?我想将字符串的第一个字符更改为“ k”(小写)
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct node
{
int data;
struct node* next;
};
void fun1(char** head)
{
printf("FUN2---%s",*head);
//this line produces a segmentation fault
**head='k';
}
void fun(char** head)
{
printf("FUN---HEAD:%s\n",*head);
fun1(head);
}
int main()
{
char *ptr="KEWIN";
printf("PTR:%p\n",ptr);
fun(&ptr);
printf("%s",ptr);
return 0;
}
最佳答案
您正在尝试更改字符串文字,具体取决于编译器的实现,该文字可能会或可能不会放在已编译程序的只读数据段中。如果将其放置在只读数据段中,则任何写入尝试都将导致段错误。将您的名字设为char name []而不是char * name会将字符串放在堆栈上,然后您就可以在其中写入内容了。另外,将char **传递给函数会增加不必要的间接级别。参见以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int data;
struct node* next;
};
void fun1(char * head)
{
printf("FUN2---%s\n", head);
// no seg fault anymore
*head='k';
}
void fun(char * head)
{
printf("FUN---HEAD:%s\n",head);
fun1(head);
}
int main()
{
char name[] = "KEWIN";
printf("PTR:%p\n",name);
fun(name);
printf("%s",name);
return 0;
}
关于c - 指向字符的指针-函数中的取消引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44613222/