在下面的代码中,行:
*end = *front;
Run Code Online (Sandbox Code Playgroud)
给出了分段错误.我在这里问了一个类似的问题,但我不确定这是不是因为我有两份num.请解释为什么它是seg-faulting.谢谢.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getPalin(char* num);
int main()
{
char* num = (char*)malloc(100);
num = "123456";
printf("%s\n", getPalin(num) );
return 0;
}
char* getPalin(char* num)
{
int length = strlen(num);
if ( length % 2 == 0 )
{
char* front = num;
char* end = num + strlen(num) - 1; //pointer to end
while( front != num + (length/2) ) //pointers not middle yet
{
*end = …Run Code Online (Sandbox Code Playgroud) 我知道这const char *是一个指向const char的指针,而是一个指向char char *const的常量指针.我在以下代码中测试它:
const char *s = "hello"; // Not permitted to modify the string "hello"
char *const t = "world"; // Not permitted to modify the pointer t
s = "hello2"; // Valid
// t = "world2"; // Invalid, gives compilation error
// *(s + 1) = 'a'; // Invalid, gives compilation error
*(t + 1) = 'a'; // Why does this not work?
Run Code Online (Sandbox Code Playgroud)
最后一行不会给出任何错误,但会导致程序意外终止.为什么要修改t不允许指向的字符串?