仅使用1个字符指针将整数值从一个变量复制到另一个变量

时间:2016-05-09 03:22:39

标签: c pointers

这是我在采访中遇到的问题之一,他问我是否可以通过仅使用字符指针将1个整数变量(比如i = 100)的值复制到另一个变量j。

main()
{        
    int i = 100;
    char *p;
    int j = 0;
   /*Write code here to copy the value of i into j  by using only the                        
   character pointer p*/
}

1 个答案:

答案 0 :(得分:2)

嗯,说我们有:

int i = 100;
int j;
char *ptr;

然后你可以写:

for (ptr = (char *)&i; ptr != (char *)(&i + 1); ++ptr)
    ((char *)&j)[ptr - (char *)&i] = *ptr;

显然这里有很多指针,但如果不使用其中的许多就不可能完成任务。

相关问题