我在嘗試變數時遇到printf()
了麻煩。char
我宣告了兩個陣列,一個用于品牌名稱,另一個用于值,根據哪個值最大,我根據陣列中的位置獲得適當的品牌名稱。
好吧,在這里列印marca
效果很好。但是當我嘗試在函式之外列印它時,它不會。
任何的想法?
最小的可重現示例:
#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
}
uj5u.com熱心網友回復:
看起來您想要的是回傳到您的字串然后列印的具有最大值的制造商品牌。為了讓我讓它作業,這里是我改變的位。
首先,我沒有定義指向字符的指標(基本上與指向“int”的指標相同),而是定義了一個與可能的最大制造商名稱一樣大的字符陣列。可能還有其他方法可以初始化字符陣列,但這是我所知道的最簡單的方法。然后,我將字串名稱作為指向您的函式的指標參考傳遞,如以下代碼片段中所述。
char marca[10];
fabricanteDeModa(marca);
在“fabricantDeModa”函式的當前迭代中,您將字符陣列參考作為引數,但就目前而言,它沒有在函式中更新。因此,我添加了我相信您正在嘗試做的事情,即將制造商的名稱存盤在該字串中。為此,我添加了一個“strcpy”命令將制造商的名稱放入您的主級別字符陣列中。
}
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
}
傳遞和更新字串(字符陣列)可能很棘手。我希望這可以為您澄清事情。
問候。
uj5u.com熱心網友回復:
marca
應該定義為achar *
或更好const char *
,并且fabricanteDeModa
應該回傳品牌名稱,而不是char
作為發布的指標。
要回傳字串,該陣列marcas
不應是char
具有自動存盤(非靜態區域變數)的二維陣列,其元素在函式回傳后將無法訪問,您可以使用字串指標陣列。
這是修改后的版本:
#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];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480146.html