如何修复警告“格式指定类型'void *'但参数具有类型'char'警告”

问题描述 投票:0回答:1

我得到了我想要的输出,但不知道如何消除这些警告。如有任何帮助,我们将不胜感激。

警告:

  1. 格式指定类型“void *”,但参数类型为“char”[-Wformat] 打印(“ 指针变量的值为%p “,*myString);

  2. “格式指定类型“void *”,但参数类型为“char”[-Wformat] printf("%p ", myString[x]);

     #include <stdio.h>
     #include <stdlib.h>
    
     int main() {
    
       char *myString = "Daniel";
       int x;
    
       printf("\nThe pointer variable's value is %p\n", *myString);
       printf("\nThe pointer variable points to %s\n", myString);
       printf("\nThe memory location for each character are: \n");
    
    
       for (x = 0;x < 7;x++){
        printf("%p\n", myString[x]);
       }
    
     return 0;
     }
    

输出:

     The pointer variable's value is 0x44

     The pointer variable points to Daniel

     The memory location for each character are: 
     0x44
     0x61
     0x6e
     0x69
     0x65
     0x6c
     (nil)
c pointers printf c-strings conversion-specifier
1个回答
4
投票

首先,这些电话

printf("\nThe pointer variable's value is %p\n", *myString);

printf("%p\n", myString[x]);

没有意义,因为您正在尝试使用字符的值作为指针值。

至于其他警告,只需将指针强制转换为类型

void *
。例如

printf("\nThe pointer variable's value is %p\n", ( void * )myString);
printf("\nThe pointer variable points to %s\n", myString);
printf("\nThe memory location for each character are: \n");


for (x = 0;x < 7;x++){
 printf("%p\n", ( void * )( myString + x ));
}
© www.soinside.com 2019 - 2024. All rights reserved.