空指针没有给出预期的结果 [英] Void Pointers do not give the expected result

查看:76
本文介绍了空指针没有给出预期的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我试图将一个字符串分配给类型为void的指针,但结果是致命的.
以下是已编译并在VC ++ 5.0上运行的代码,以供您参考.请帮我解决这个问题.

Hi,
I am trying to assign a string to a pointer of type void but the result is fatal.
The below is the code is compiled and ran on VC++5.0 for your reference. Please help me fix this.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char s1[] = "Hi Thomas";
    void* vpTmp;
    char* s2;
    int idx = 0;


    vpTmp = ( char * ) malloc( strlen( s1 ) + 1 );
    while( s1[idx] != '\0' )
    {
        *( char * )vpTmp = s1[idx++];
        ( (int *)vpTmp )++;
    }
    ( (int * )vpTmp )++;
    *( char * )vpTmp = '\0';
    idx++;
    (int * )vpTmp = ( int * )vpTmp - idx;
    printf("The string is : %s\n", vpTmp );
    s2 = ( char * ) vpTmp;
    printf("The string is: %s\n", s2 );
    return 0;
}

推荐答案

每当对指针执行指针算术运算时,结果始终取决于指针类型(实际上是指针类型的大小) ).在这里,您在将void指针强制转换为int指针之后增加了它.因此,指针将按sizeof(int)递增,而不按sizeof(char)递增.

请参阅 [
Whenever you perform the pointer arithmetic operation on pointer, the result is always dependent on the pointer type (actually the size of type of the pointer). Here you''re incrementing the void pointer after casting it to int pointer. Because of which the pointer will be incremented by sizeof(int) not by the sizeof(char).

Please refer to ''Pointer Arithmetic'' section of this [^]article.

Have a nice pointer calculations !!!


"++"不会以常数1递增,而是以"sizeof(item)"递增,因此,如果您键入as(int *),然后"++"将递增到下一个INTEGER.用数学术语来说,指针中包含的地址将增加4.这根本不是您想要的.

如果您在每次使用时都将其视为指向char(char *)的指针,则应这样声明它.用指针进行数学运算非常棘手,使用重铸指针进行数学运算非常危险(哦,等等,您发现了).
"++" does not increment by the constant 1, it increments by the "sizeof(item)" so, if you type is as (int *) then "++" will increment to the next INTEGER. In math terms, the address contained in the pointer will be incremented by 4. Not at all what you want.

If you are treating it as a pointer to char (char *) in every use, declare it as such. Doing math with pointers is tricky, doing math on re-cast pointers is downright dangerous (oh, wait, you found that out).


vpTmp = ( char * ) malloc( strlen( s1 ) + 1 );
    while( s1[idx] != '\0' )
    {
        *( char * )vpTmp = s1[idx++];
        ( (int *)vpTmp )++;
    }
    ( (int * )vpTmp )++;
    *( char * )vpTmp = '\0';
    idx++;
    (int * )vpTmp = ( int * )vpTmp - idx;
    printf("The string is : %s\n", vpTmp );
    s2 = ( char * ) vpTmp;
    printf("The string is: %s\n", s2 );
    return 0;
}


这篇关于空指针没有给出预期的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆