D Seller
D Seller

Reputation: 43

initialization creates pointer from integer without a cast

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

Upvotes: 0

Views: 41

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12668

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.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

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.

Upvotes: 1

Related Questions