This question already has answers here:
What does void* mean and how to use it?
                                
                                    (10个回答)
                                
                        
                                2年前关闭。
            
                    
我正在尝试制作一个带空指针的计算器,该指针称为yourVal,查看第一个字节并确定它是'*'还是'/'。根据符号,我将字节3 + 4、5 + 6和7 + 8相乘。说我有* 1234567。我乘以23 * 45 *67。通过除法,我将字节5(45)除以字节3(23)。我是C语言中的指针的新手,我真的不知道如何为void指针设置值。当我主要执行以下操作时

void *yourVal;
*yourVal = "*1234567";
printf("%s\n", yourVal);


我无法取消引用空指针。但是我尝试了使用char指针,但是我遇到了同样的问题。
这是我的计算器功能代码。根据我是否使用printf,得出不同的结果。

int calculator(void *yourVal){
  char *byteOne;
  short int *byteThree, *byteFive, *byteSeven;
  int value;

  byteOne = (char *)yourVal;
  byteThree = (short int *)yourVal+2;
  byteFive = (short int *)yourVal+4;
  byteSeven= (short int *)yourVal+6;

  if(*byteOne == '*') {
    value = *byteThree * *byteFive * *byteSeven;
    printf("You multiplied\n");
  }
  else if(*byteOne == '/') {
    if (*byteThree == 0) {
        value = 0xBAD;
        printf("Your input is invalid\n");
    }
    else {
        value = *byteFive / *byteThree;
        printf("You divided\n");
    }
  }
  else {
    value = 0xBAD;
    printf("Your input is invalid\n");
  }
}


该除法根本不起作用,并且乘法仅获取一位数。任何提示将不胜感激。我查看了各种资源,但没有看到如何有效地使用空指针。另外,除了printf之外,我不能使用任何库函数,这是学校的任务,因此请不要给我太多破坏者或为我做的事情。我们得到了一个提示,那就是将yourVal转换为一个结构。但是我迷失了。谢谢

最佳答案

byteOne = (char *)payload;
byteThree = (short int *)yourVal+2;
byteFive = (short int *)yourVal+4;
byteSeven= (short int *)yourVal+6;


这并没有按照您的想法做。如果要读取这些位置的数字,则需要执行类似操作。

char* Value = yourValue;
unsigned byteOne, byteThree, byteFive, byteSeven;
byteOne = Value[0] - '0';
byteThree = Value[2] - '0';
byteFive = Value[4] - '0';
byteSeven = Value[6] - '0';


我在这里所做的是读取该位置的字节并减去'0'ASCII值以获得该字符的数值。但是同样,这仅适用于单个字符。

如果需要阅读更多字符,则必须使用库功能,例如sscanfatoi

关于c - 在C中的void指针中查看和使用单个字节,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46357981/

10-11 23:12
查看更多