为什么指针算术不在char *函数中工作

时间:2017-08-01 21:42:06

标签: c string

消息:

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

当我的函数类型不为空时,我无法理解为什么我不能使用指针算法。看一下这个例子:

我们要说我必须编写一个能够删除''字符串中第一个单词之前的所有空格。 例如,如果我们有一个char数组:

"    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!= '\0') {
            *q = *p; 
            p++; 
            q++;
        } /*copying the text*/

        *q = '\0'; /*If I had n spaces at the beginning the new string has n characters less */
    }
    return s;
} 

1 个答案:

答案 0 :(得分:2)

这是一个函数实现,它具有你想要的返回类型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] != '\0' ) ++length;

    char *p = malloc( length + 1 );

    if ( p != NULL )
    {
        size_t i = 0;
        while ( ( p[i] = s[i + blanks] ) != '\0' ) ++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;
}