代码几处问题:
1.TentoTwo()函数在使用前,没有声明,应在第2 3 行插入一行函数声明语句:int *TentoTwo(int x);
2.在TentoTwo()函数里定义的两个数组都是局部变量,待TentoTwo()函数运行结束,这两个数组的生命期也随之结束,所以return h; 是个野指针。建议把数组yyx[]定义在主函数里,然后以形参的方式传递。
修改如下,改动处见注释,供参考:
#include <stdio.h>
#include <string.h>
int TentoTwo(int x, int yyx[]); // 修改
int main()
{
int x, yyx[20], n; // 修改
scanf("%d", &x);
n = TentoTwo(x, yyx); // 修改
for (int i = 0; i < n; i++)// 修改
printf("%d", yyx[i]);
return 0;
}
int TentoTwo(int x, int yyx[]) // 修改
{
int xyy[20], i = 0, j, t;
while (x){ // 修改
xyy[i++] = x % 2;
x /= 2;
}
t = i;
for(i--, j = 0; i >= 0; i--)
yyx[j++] = xyy[i];
return t; // 修改
}
二进制这样写:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num,a[33];
scanf("%d",&num);
int tmp=0;
while(num)
{
tmp++;
a[tmp]=num%2;
num/=2;
}
for(int i=tmp;i>=1;i--) printf("%d",a[i]);
}
*h=yyx
而yyx是函数的局部变量,返回以后这个堆栈上的内存就无效了。
要malloc新的内存再返回
1、图一及其结果
2、图二及其结果
#include<iostream>
using namespace std;
int main()
{
int num;
int arr[33];
scanf("%d",&num);
int tmp=0;
while(num)
{
tmp++;
arr[tmp]=num%2;
num/=2;
}
for(int i=tmp;i>=1;i--)
{
cout<<a[i];
}
}
感谢回答,我是想通过指针函数的方式进行进制转换,这样子复习一下我的指针那一方面知识,谢谢道友们指点,我发现我的函数没有申明,并且还有很多遗漏。