将char *数组传递给另一个函数,c中的指针有问题

时间:2012-02-07 08:23:33

标签: c pointers

嘿,我无法将正确的值存储到CHANNELS字符数组中。我真的认为这可能是我指针的一个简单问题。我“想”我理解当你声明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;
}

1 个答案:

答案 0 :(得分:0)

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中存储的地址的基础开始覆盖内存,并且根据内存分配给自动变量的方式将被覆盖,这是一种未定义的行为。
  3. 尝试动态分配您在bitEnter函数中输入的字符串,然后将其添加到CHANNELS