c语言 - 为什么指针算术在 char* 函数中不起作用



消息:

/usr/local/webide/runners/c_runner.sh: line 54: 20533 Segmentation fault
nice -n 10 valgrind --leak-check=full --log-file="$valgrindout" "$exefile"

我不明白为什么当我的函数类型不为空时我不能使用指针算术。看看这个例子:

假设我必须编写一个函数来"擦除"字符串中第一个单词之前的所有空格。 例如,如果我们有一个字符数组:

"    Hi everyone"

它应该在函数修改后产生"Hi everyone"

这是我的代码,当而不是char* EraseWSbeforethefirstword()我有
void EraseWSbeforethefirstword.

当函数返回一个对象char*它甚至无法编译时。

char* EraseWSbeforethefirstword(char *s) {
char *p = s, *q = s;
if (*p == ' ') { /*first let's see if I have a string that begins with a space */
while (*p == ' ') {
p++;
} /*moving forward to the first non-space character*/
while (*p!= '') {
*q = *p; 
p++; 
q++;
} /*copying the text*/
*q = ''; /*If I had n spaces at the beginning the new string has n characters less */
}
return s;
} 

下面是一个函数实现,其返回类型char *如您所愿。

#include <stdio.h>
char *  EraseWSbeforethefirstword( char *s ) 
{
if ( *s == ' ' || *s == 't' )
{
char *p = s, *q = s;
while ( *p == ' ' || *p == 't' ) ++p;
while ( ( *q++ = *p++ ) );
}
return s;
}
int main(void) 
{
char s[] = "t Hello World";
printf( ""%s"n", s );
printf( ""%s"n", EraseWSbeforethefirstword( s ) );
return 0;
}

程序输出为

"    Hello World"
"Hello World"

请注意,您不能修改字符串文本。因此,程序将具有未定义的行为,如果而不是数组

char s[] = "t Hello World";

将声明一个指向字符串文字的指针

char *s = "t Hello World";

如果您希望函数可以处理字符串文字,则该函数必须动态分配一个新数组并返回指向其第一个元素的指针。

如果您可能不使用标准 C 字符串函数,则该函数可以如下所示

#include <stdio.h>
#include <stdlib.h>
char *  EraseWSbeforethefirstword( const char *s )
{
size_t blanks = 0;
while ( s[blanks] == ' ' || s[blanks] == 't' ) ++blanks;
size_t length = 0;
while ( s[length + blanks] != '' ) ++length;
char *p = malloc( length + 1 );
if ( p != NULL )
{
size_t i = 0;
while ( ( p[i] = s[i + blanks] ) != '' ) ++i;
}
return p;
}
int main(void) 
{
char *s= "t Hello World";
printf( ""%s"n", s );
char *p = EraseWSbeforethefirstword( s );
if ( p ) printf( ""%s"n", p );
free( p );
return 0;
}

最新更新