Kiran Cyrus Ken
Kiran Cyrus Ken

Reputation: 389

Why does passing a char array as argument in a function and trying to modify inside the function shows segmentation error?

I have declared an array of char variables as below:

char word[256];
char plural[256];

It takes input inside the main function and copies to plural variable as below:

scanf("%s",&word);
strcpy(plural,word);

The input I provided is "Baby".

The main method call another function pluralize by passing both the variables as arguments as below:

void pluralize(word,plural);

Here is what I want to do with the pluralize method:

void pluralize(char word[], char plural[]){
    char textToBeAdded[] = "IES";   
    int i = strlen(plural);
    plural[i-1] = '\0';
    plural = strcat(plural, textToBeAdded);
    printf("Word is %s and plural is %s", word, plural);
    printf("\nRule is 1\n");
}

I am not using char* and using char[], so it should be modifiable. But it shows a segmentation run time error. Why and what am I doing wrong?

Upvotes: 1

Views: 47

Answers (1)

P.W
P.W

Reputation: 26800

One problem is with this statement:

scanf("%s",&word);

word is an array of chars. So to read into it, you just have to:

scanf("%s",word);

Upvotes: 2

Related Questions