簡體   English   中英

將char *數組傳遞給另一個函數,C中的指針麻煩

[英]Passing char * array to another function, Pointer trouble in c

嘿,我無法將正確的值存儲到CHANNELS char數組中。 我真的認為這可能是一個簡單的問題。 我“認為”我了解,當您聲明char * CHANNELS [6]時,您正在創建一個指針數組。 所以我在第三個參數中的switch語句案例1 CHANNELS中通過,我沒有得到正確的值。 任何幫助都很棒! 一些背景知識:我正在讀取6個“通道”,每個通道都有6個二進制值。

void binEnter(void *channel, char *CHANNELS[6], int i){
redo:
    printf("Enter binary value for Channel %d: ",i);
    scanf("%s",(UCHAR *)channel);
    if (strlen(channel)!=6) {
        printf("Error entry must be six digits!\n");
        goto redo;
    }
    char *string = channel;
    int j;
    for (j = 0; j < 6; j++){
        if ((string[j] != '0') && (string[j] != '1')){
            printf("Error did not enter a binary number!\n");
            goto redo;
        }
    }
CHANNELS[i]=channel;
printf("Channel %d is stored as %s\n",i,CHANNELS[i]);

}

int main(){
int selection;
UCHAR channel0;
UCHAR channel1;
UCHAR channel2;
UCHAR channel3;
UCHAR channel4;
UCHAR channel5;
char *CHANNELS[6];
float vRefVal[6];
//char *data[5];
float volt =0;
do {
start:
    promptUser();
    scanf("%d",&selection);
    switch (selection) {
        case 1:
            binEnter(&channel0, CHANNELS,0);
            binEnter(&channel1, CHANNELS,1);
            binEnter(&channel2, CHANNELS,2);
            binEnter(&channel3, CHANNELS,3);
            binEnter(&channel4, CHANNELS,4);
            binEnter(&channel5, CHANNELS,5);
            int i;
            for (i=0; i<6; i++) {
                printf("Channel %d is %s in main\n", i, CHANNELS[i]);
            }
            goto start;

        case 2:
            goto start;
        case 3:
            enterVolt(&volt);
            printf("Volt = %f\n",volt);
            goto start;
        case 4:
            if (volt) {
                vRefCal(&volt, CHANNELS, vRefVal);
                printVref(vRefVal);
                goto start;
            }
            else{
                printf("Must enter input Vref first!\n");
                goto start;
            }
        default:
            break;
    }
} while (selection!=5);
return 1;
}

UCHAR channel0;

你已經通過

binEnter(&channel0, CHANNELS,0);

bitEnter的原型為void binEnter(void *channel, char *CHANNELS[6], int i)

但隨后您要做: scanf("%s",(UCHAR *)channel);

  1. 如果要將其作為字符串處理,為什么將其傳遞為void *
  2. 您正在嘗試輸入一個字符串,其類型為UCHAR (我認為這是一個無符號字符)。 這樣做將從存儲在channel中的地址的基數開始覆蓋內存,並且取決於將內存分配給自動變量的方式,它們將被覆蓋,這是不確定的行為。

嘗試動態分配您在bitEnter函數中輸入的字符串,然后將其添加到CHANNELS嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM