将char *传递给函数会返回与传递char []不同的结果吗?

时间:2017-06-02 03:56:52

标签: c arrays string pointers

我在C中编写一个函数来从字符串(* s)中获取下一个单词并将其复制到缓冲区(* w)中。它返回单词的第一个字符。

当输入字符串是char指针(char * text)时,它工作正常,但是当我将类型更改为char数组(char [MAXTEXT])时程序崩溃。

这让我感到困惑,因为我认为编译器'腐朽'的char数组无论如何都会变成char指针。据我所知,输入是char指针还是char数组应该没有区别?

(声明位于第10行char *text = "This should return the first word";,当更改为char text[MAXTEXT] = "This should return the first word";时会崩溃

#include <stdio.h>
#include <ctype.h>

#define MAXTEXT 1000

int getword(char *inp, char *out, int lim);

void main()
{
    char *text = "This should return the first word";
    char *word;
    int i, c;

    printf("%c", getword(text, word, MAXTEXT));
    printf("%s", word);
}

int getword(char *s, char *w, int lim)
{
    static int bufp = 0;
    char c;
    char *word = w;

    while (isspace(c = s[bufp++]));

    if (c != EOF)
        *w++ = c;
    else if (!isalpha(c))
    {
        *w = '\0';
        return c;
    };

    for (; --lim > 0; bufp++)
        if (isalpha(c = s[bufp]) || c == '\'')
            *w++ = s[bufp];
        else
            break;
    *w = '\0';
    return word[0];
}

1 个答案:

答案 0 :(得分:2)

问题在于,对于指针word,您还没有分配任何内存。简单地分配内存将解决问题。 你的数组实现:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define MAXTEXT 1000

char getword(char *inp, char *out, int lim);

int main()
{
    char text[100],word[100];
    // char *text = (char*)calloc(100,sizeof(char));
    strcpy(text,"This should return the first word");
    // char *word = (char*)calloc(100,sizeof(char));
    int i, c;

    printf("%c", getword(text, word, MAXTEXT));
    // printf("%s", text);
    return 0;
}

char getword(char *s, char *w, int lim)
{
    static int bufp = 0;
    char c;
    char *word = w;

    while (isspace(c = s[bufp++]));

    if (c != EOF)
        *w++ = c;
    else if (!isalpha(c))
    {
        *w = '\0';
        return c;
    };

    for (; --lim > 0; bufp++)
        if (isalpha(c = s[bufp]) || c == '\'')
            *w++ = s[bufp];
        else
            break;
    *w = '\0';
    return word[0];
}