我正在通过try 实现一个能够交换字符串和数组的通用交换函数来学习C语言.我认为这是可能的,因为字符串和数组本质上是内存中的数组,而我交换的不是实际的字节,而只是指针.以下是我的实现:
#include "stdio.h"
void swap(void **a, void **b) {
void *tmp;
tmp = *b;
*b = *a;
*a = tmp;
}
void print_array(char *c, int size) {
for (int i = 0; i < size; ++i) {
printf("%c ", c[i]);
}
printf("\n");
}
int main() {
char *h = "hell";
char *w = "world";
printf("%s %s\n", h, w);
swap((void **)&h, (void **)&w);
printf("%s %s\n", h, w);
char c[5] = { 'a', 'e', 'i', 'o', 'u' };
char d[3] = { '1', '2', '3' };
print_array(c, 5);
print_array(d, 3);
swap((void **)&c, (void **)&d);
return 0;
}
结果是:
hell world
world hell
a e i o u
1 2 3
*** stack smashing detected ***: terminated
Aborted (core dumped)
正如您所看到的,这个通用的交换函数可以交换两个字符串,但当输入是数组时,它会触发核心转储.我不明白我对指针和数组的理解哪一部分是错误的.