dav
dav

Reputation: 936

Passing char * to function returns different results than passing char []?

I am writing a function in C to get the next word from a string (*s) and copy it into the buffer (*w). It returns the first char of the word.

It works fine when the input string is a char pointer (char *text), but when I change the type to a char array (char [MAXTEXT]) the program crashes.

This is confusing me, as I thought the compiler 'decayed' char arrays into char pointers anyway. To my belief, whether the input is a char pointer or a char array shouldn't make a difference?

(The declaration is at line 10 char *text = "This should return the first word";, which crashes when changed to 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];
}

Upvotes: 1

Views: 91

Answers (1)

Jaskirat Singh
Jaskirat Singh

Reputation: 82

The problem is that for the pointer word, you haven't allocated any memory. Simply allocating memory will fix the problem. Your array implementation:

#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];
}

Upvotes: 2

Related Questions