我的C代码不起作用

时间:2014-05-27 06:57:33

标签: c pointers

我试图编写一个程序,接受来自用户的字符串,然后将每个字符转换为相应的8位二进制代码,并将其存储在char数组(或指针类型的char数组)中。我有以下代码,但它给我错误(分段)。

更新 我已经初始化了指针p,因为很多人都指出了谢谢! 但我仍然得到奇怪的输出。

请帮助: -

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

int xstrlen (char *s) //for later use
{
int length = 0 ;
while ( *s != '\0' )
{
length++ ;
s++ ;
}
return ( length ) ;
}

char* showbits(int n)
{
int i, k, andmask ;

char* p=(char *)malloc(9);
for ( i = 7 ; i >= 0 ; i-- )
{
    andmask = 1 << i ;
    k = n & andmask ;

    if(k==0)
    {
       strcat(p,"0");
    }

    else
    {
       strcat(p,"1");
    }
}
//*p='\0'; Have removed this line
return p;
}


void msg2bits(char *msg)
{

    char* bits;
 //   char *bits=(char*)malloc(9);
    int x;
    int i=0;


   while(*msg!='\0')
   {
       x=(int)msg[i];
      // char *bits=(char*)malloc(9);
       bits=showbits(x);

       puts(bits);
       msg++;
       i++;
      // free(bits);
    }
}


int main(int argc,char *argv[])
{
    char *msg="ABCD";

    msg2bits(msg);
    getch();
    return 0;
}

我已经将showbits和msg2bits作为两个独立的函数,因为你可能会想到为什么不将它们组合起来因为我会在这个问题上进一步处理函数msg2bits。

先谢谢大家!

P.S由于我的声誉*叹气,我无法上传输出图像

1 个答案:

答案 0 :(得分:0)

在此片段中:

 while(*msg!='\0')
       {
           x=(int)msg[i];
          // char *bits=(char*)malloc(9);
           bits=showbits(x);

           puts(bits);
           msg++;
           i++;
          // free(bits);
        }

例如msg =“1234”

i = 0 & msg = "1234" :
x = 1
i++; msg++ ==> i=1 & msg = "234" :
x = 3
.
.
.

你通过在同一个循环中递增两次来踩过你的一些msg字符

相关问题