pointers to different types at argument #1
时间: 2024-04-09 18:28:58 浏览: 143
Introduction to C++ Programming Understanding Pointers 无水印pdf
In C, you can use void pointers (void *) to pass pointers to different types as arguments. A void pointer is a generic pointer type that can be used to point to any data type. However, when using void pointers, you need to ensure proper typecasting when accessing the data pointed to by the void pointer.
Here's an example of passing pointers to different types using void pointers:
```c
#include <stdio.h>
void printValue(void *ptr, char type) {
switch (type) {
case 'i':
printf("Value: %d\n", *(int*)ptr);
break;
case 'f':
printf("Value: %.2f\n", *(float*)ptr);
break;
case 'c':
printf("Value: %c\n", *(char*)ptr);
break;
}
}
int main() {
int intValue = 10;
float floatValue = 3.14;
char charValue = 'A';
printValue(&intValue, 'i');
printValue(&floatValue, 'f');
printValue(&charValue, 'c');
return 0;
}
```
In this example, the `printValue` function takes a void pointer `ptr` and a character `type` to determine the type of the value pointed to by `ptr`. Inside the `switch` statement, the `ptr` is typecasted to the respective type (int, float, or char) before dereferencing it to print the value.
Output:
```
Value: 10
Value: 3.14
Value: A
```
By using void pointers and typecasting, you can pass pointers to different types as arguments in C.
阅读全文