Dynaheart
Dynaheart

Reputation: 3

C - Why does my string return Null when sending it to a function?

I am a total beginner, but I am doing a project for school and I just can't seem to get it working.

The goal is simple: scan 5 strings, count their vowels and then sort it alphabetically using functions.

I have the vowel part sorted out, but when I send the already scanned strings to my function, it gets read as null so I can't sort it there.

I'll show you the code very simplified so I can highlight the problem more easily (without the bubble sort):

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

char abc(char nombres[])
{
    printf("\n%s", nombres[3]);
}
int main()
{
    char nombres[20][20];
    printf("Ingrese 5 nombres:\n")

    for (int i = 0; i < 5; i++)
    {
        scanf(" %s", nombres[i]);
    }
    
    abc(nombres);

    return 0;
}

In my imagination, it should display the third input that was scanned, but the output reads:

Ingrese 5 nombres
juan
alberto
lautaro
milo
beatriz

(Null)

Hopefully, you have already spotted the problem, if so, please help me correct my code. I can send the rest if you want, I just trimmed it for the sake of simplicity.

Upvotes: 0

Views: 169

Answers (1)

dbush
dbush

Reputation: 225344

What you're passing to the function isn't compatible with the parameter type.

The function expects a parameter of type char [], which as a function parameter is exactly the same as char *. What you're passing to it is a char [20][20]. Your compiler should have warned you about this. It should also have warned you about sending nombres[3] inside of abc which has type char, i.e. a single char and not a string like the %s format specifier expects.

You need to change the parameter type to the function to match what you're passing to it and how you're using it.

char abc(char nombres[20][20])

Upvotes: 1

Related Questions