为什么用 char* 替换 char[] 会产生总线错误?
Why does replacing char[] with char* produce bus error?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int comp(const void *a, const void *b) {
const char *ia = (const char*)a;
const char *ib = (const char*)b;
return (*ia - *ib);
}
int main(int argc, char *argv[]){
char *temp1 = "hello";
char temp[] = "hello";
qsort(temp, strlen(temp), sizeof(char), comp);
printf ("%s\n", temp);
/*
qsort(temp1, strlen(temp1), sizeof(char), comp);
printf ("%s\n", temp1);
*/
}
在这个对字符串进行排序的 qsort 调用中,此处显示的代码按如下所示工作(我的意思是它对字符串“hello”进行排序)。但是当我取消注释最后两行的注释时(从而对 temp1 进行排序),它在 mac pro 上崩溃并出现总线错误。 cc上的版本信息显示:
Apple LLVM 版本 10.0.0 (clang-1000.10.44.4)
目标:x86_64-apple-darwin17.7.0
线程模型:posix
我想知道为什么它会产生总线错误。
char *temp1 = "hello"; // pointer to a const string
temp1
指向字符串文字。你不能修改它。 qsort()
函数试图修改它。这就是错误的原因。
char temp[] = "hello"; //const pointer to a string
这里可以修改数组内容。这就是它起作用的原因。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int comp(const void *a, const void *b) {
const char *ia = (const char*)a;
const char *ib = (const char*)b;
return (*ia - *ib);
}
int main(int argc, char *argv[]){
char *temp1 = "hello";
char temp[] = "hello";
qsort(temp, strlen(temp), sizeof(char), comp);
printf ("%s\n", temp);
/*
qsort(temp1, strlen(temp1), sizeof(char), comp);
printf ("%s\n", temp1);
*/
}
在这个对字符串进行排序的 qsort 调用中,此处显示的代码按如下所示工作(我的意思是它对字符串“hello”进行排序)。但是当我取消注释最后两行的注释时(从而对 temp1 进行排序),它在 mac pro 上崩溃并出现总线错误。 cc上的版本信息显示:
Apple LLVM 版本 10.0.0 (clang-1000.10.44.4) 目标:x86_64-apple-darwin17.7.0 线程模型:posix
我想知道为什么它会产生总线错误。
char *temp1 = "hello"; // pointer to a const string
temp1
指向字符串文字。你不能修改它。 qsort()
函数试图修改它。这就是错误的原因。
char temp[] = "hello"; //const pointer to a string
这里可以修改数组内容。这就是它起作用的原因。