Printing char value using reference

I’m having trouble trying to printf() a char variable.

I declare two arrays, one for the brand names and the other for the values, based on which value is the biggest I get the appropriate brand name based on the position in the array.

Well, printing marca here works perfectly. But when I try to print it outside the function it doesn’t.

Any idea?

Minimal reproducible example:

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

void fabricanteDeModa(char *);

int main()
    char marca;
    printf("%s", marca); //Not working (already tried changing to %c)

    return 0;

void fabricanteDeModa(char *marca)
    int apple = 5;
    int xiaomi = 10;
    int samsung = 7;
    int htc = 12;
    int lg = 15;
    int zte = 10;
    int nokia = 2;

    char marcas[7][10] = {

    int valores[7] = { apple, xiaomi, samsung, htc, lg, zte, nokia };
    int i;
    int maxVal = valores[0];
    int pos = 0;

    for (i = 1; i < 7; ++i)
        if (valores[i] > maxVal)
            maxVal = valores[i];
            // Find the index of the max value
            pos = i;
    marca = marcas[pos];
    printf("%s\n", marca); //This Works

>Solution :

What it looks like you want is the manufacturer brand with the largest value returned to your string and then printed. In order for me to get that to work, here are the bits I changed.

First, instead of defining a pointer to a character (which is fundamentally the same as a pointer to an "int") I defined a character array that was as large as the largest possible manufacturer name. There are probably other ways to initialize the character array, but this is the simplest way I know. I then pass the string name as the pointer reference to your function as noted in the following code snippet.

char marca[10];

In your current iteration of the "fabricantDeModa" function, you have the character arrary reference as your parameter, but as it currently stands, it was not getting updated within the function. So, I added what I believe you were attempting to do which is store the manufacturer’s name within that string. To do that I added a "strcpy" command to place the manufacturer’s name into your main level character array.

    strcpy(marca, marcas[pos]);   /* Added this code */
    printf("Largest element = %d\n", pos);
    printf("La marca de moda es : %s\n", marcas[pos]); //This Works

Passing and updating strings (character arrays) can be tricky. I hope this clarifies things for you.


Leave a Reply