0

My program is designed to make the plural of a noun. The error comes from the line "char *pstr = userNoun[lengthStr - 1];". Could someone tell me what my mistake was here?

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void pluralNoun(char userNoun[27]){
    int lengthStr = 0;
    const char caseOne[2] = "es";
    const char caseTwo[2] = "s";
    lengthStr = strlen(userNoun);
    char *pstr = userNoun[lengthStr - 1];

    if(strncmp(pstr - 1, "ch", 2) == 0){
        strcat(userNoun, caseOne);
    }
    else if(strncmp(pstr - 1, "sh", 2) == 0){
        strcat(userNoun, caseOne);
    }
    else if(*pstr == 's'){
        strcat(userNoun, caseOne);
    }
    else if(*pstr == 'y'){
        userNoun[lengthStr - 1] = 'i';
        strcat(userNoun, caseOne);
    }
    else {
        strcat(userNoun, caseTwo);
    }
    printf("The plural of your noun is %s\n", userNoun);
}

int main(void){
    char userVar[25];

    printf("Enter a noun no more than 25 characters in length in lower case letters:\n");
    scanf("%s", userVar);
    pluralNoun(userVar);

    return 0;
}
2
  • You meant: char *pstr = &userNoun[lengthStr - 1]; Commented Oct 22, 2016 at 20:14
  • 1
    userNoun[lengthStr - 1] is a char. If you want a pointer to the address of the char, you should do &(userNoun[lengthStr - 1]), or user pointer arithmetic directly. Commented Oct 22, 2016 at 20:15

2 Answers 2

1

You have two errors:

  • The one causing the problem is a missing address-of operatorin userNoun[lengthStr-1] expression
  • The second problem is the size of "es" array: one[2] is too small to fit null terminator after "es", so you would end up with undefined behavior

Since strcat does not reallocate, make sure that the buffer has enough space for the additional suffix and the null terminator.

Sign up to request clarification or add additional context in comments.

1 Comment

Some more errors: The input buffer is too small, ref the text string "no more than 25 characters" and scanf's format string has no upper limit. There's also no checks on the input, so e.g. an empty string (User presses enter) will cause array indexing out of bounds[lenghtStr - 1]
0

The error you point to on your question means you are trying to initialize the pointer variable char *pstr with the value of userNoun[lengthStr - 1], which is a char value (and not a char pointer)

The compiler message probably sounds a little imprecise, but it is. The char value is taken as a number and the target type isn't.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.