c - 对字符串使用通用指针

标签 c

<分区>

我正在尝试一个示例程序来了解通用交换功能。

/* 一个简单的通用交换函数 */

#include<stdio.h>
#include<string.h>

void swap(void* xp,void* yp,int size){
        //void temp = *xp; // we cant declare a variable as void , as we need to konw to de-reference as its not specifying any size info
        // Hence used the smallest type info - char
        char buffer[size];
        memcpy(buffer,xp,size);
        memcpy(xp,yp,size);
        memcpy(yp,buffer,size);
}

int main(){
        int a = 10;
        int b = 20;
        double d=1.34;
        double e=2.34;
        char* s = "Hello";
        char* t = "World";
        printf("\n a : %s b : %s \n",s,t);
        swap(s,t,sizeof(char*));
        printf("\n a : %s b : %s \n",s,t);
        return 0;
}

当我使用函数调用 swap(s,t,sizeof(char*)) 运行上述程序时,我遇到了段错误。但是,如果我使用 swap(&s,&t,sizeof(char*)) 运行它,我不会遇到任何段错误。

gdb o/p:

Breakpoint 2, swap (xp=0x4007ac, yp=0x4007b2, size=8) at swap_generic1.c:5
5   void swap(void* xp,void* yp,int size){
(gdb) s
8       char buffer[size];
(gdb) s
9       memcpy(buffer,xp,size);
(gdb) s
10      memcpy(xp,yp,size);
(gdb) s

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b64fe4 in ?? () from /lib/x86_64-linux-gnu/libc.so.6

问题的原因可能是什么。是当作为 s 和 t 传递时,参数分别分配有字符串“Hello”和“World”的地址,并且指针递增到其他位置以获取值。

最佳答案

您正在使用 sizeof (char *) 调用交换函数,因此您希望只交换指针。但是您没有将指针传递给指针,而是传递了指针本身的值。

这将使 swap() 尝试交换字符串中的 sizeof (char *) characters,这是不允许的,因为字 rune 字生成不可写入的常量数据。

你应该这样调用它:

swap(&s, &t, sizeof s);

只是交换指针值,而不是移动任何字符数据。

关于c - 对字符串使用通用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24488394/

相关文章:

c - 文件内的值不会被替换

c - K&R fopen 和 fillbuf 中 C 中的段错误

c - 在编写干净的 C 代码时利用 ARM 未对齐的内存访问

c - 内存不足..怎么办?

c - 在 C 编程中,我试图使用指针反向打印我的数组,但我似乎无法得到它

iphone - Objective-C 中的纺织品解析?

c - 使用宏简化释放许多指针

c - 获取和箭头代码

比较 C 中的结构

c - 如何在c中创建结构链表