'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;
fabricanteDeModa(&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] = {
"apple",
"xiaomi",
"samsung",
"htc",
"lg",
"zte",
"nokia"
};
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 1:[1]
marca should be defined as a char * or better const char * and fabricanteDeModa should return the brand name, not take a pointer to char as posted.
To return the string, the array marcas should not be a 2D array of char with automatic storage (non-static local variable) whose elements will not be accessible after the function returns, you can instead use an array of string pointers.
Here is a modified version:
#include <stdio.h>
const char *fabricanteDeModa(void);
int main() {
const char *marca = fabricanteDeModa();
printf("%s\n", marca);
return 0;
}
const char *fabricanteDeModa(void) {
int apple = 5;
int xiaomi = 10;
int samsung = 7;
int htc = 12;
int lg = 15;
int zte = 10;
int nokia = 2;
const char *marcas[7] = { "apple", "xiaomi", "samsung", "htc", "lg", "zte", "nokia" };
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];
// Update the index of the max value
pos = i;
}
}
printf("Largest element = %d\n", pos);
printf("La marca de moda es : %s\n", marcas[pos]); //This Works
return marcas[pos];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
