我正在尝试使用 strcpy 将一些字符串复制到结构中的字符串。我正在发布代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct floating_point{
char sign[2];
char exponent[9];
char fraction[24];
}FLOATING_POINT;
FLOATING_POINT stringToFloatingPoint(char* str){
struct floating_point fp;
char *integer_str,*fraction_str,*integer_bin,*fraction_bin,*sign;
sign=(char*)malloc(2*sizeof(char));
int i=1,integer=0,fraction=0,comma=0,remainder=0,size=0;
double fraction_double;
//str=(char*)malloc(200*sizeof(char));
//str="108,53";
char * pch=(char*)malloc((strlen(str)+1)*sizeof(char));
pch=strchr(str,',');
if(pch==NULL){
pch=str+strlen(str);
}
comma=pch-str;
integer_str=(char*)malloc((comma+1)*sizeof(char));
strncpy(integer_str,str,comma);
integer_str[comma]='\0',
integer=atoi(integer_str);
fraction_str=(char*)malloc((strlen(str)-comma+2)*sizeof(char));
strncpy(fraction_str,str+comma+1,strlen(str)-1);
fraction_str[strlen(str)-comma]='\0';
fraction=atoi(fraction_str);
printf("%d",fraction);
printf("%s",fraction_str);
if(integer<0){
strcpy(sign,"1");
integer=-1*integer;
}
else{
strcpy(sign,"0");
}
size=(int)(log(integer)/log(2))+2;
integer_bin=(char*)malloc(size*sizeof(char));
while(integer>0){
remainder=fmod(integer,2);
integer=integer/2;
*(integer_bin+size-i-1)=(char)(remainder+48);
i++;
}
*(integer_bin+size-i-1)=(char)(integer+48);
*(integer_bin+size-1)='\0';
printf("%s\n",integer_bin);
fraction_bin=(char*)malloc(24*sizeof(char));
fraction_double=atof(fraction_str);
fraction_double=fraction_double/(pow(10,strlen(fraction_str)));
printf("frac= %f",fraction_double);
i=0;
while((i<23)&&fraction_double!=0){
fraction_double=2*fraction_double;
if(fraction_double<1){
*(fraction_bin+i)='0';
}
else{
fraction_double=fraction_double-1;
*(fraction_bin+i)='1';
}
i++;
}
*(fraction_bin+i)='\0';
printf("\n%s",integer_bin);
printf("\n%s",fraction_bin);
size=strlen(integer_bin);
for(i=0;i<strlen(fraction_bin)-(size-1);i++){
*(fraction_bin+strlen(fraction_bin)-1-i)=*(fraction_bin+strlen(fraction_bin)-size-i);
}
for(i=1;i<size;i++){
*(fraction_bin+i-1)=*(integer_bin+i);
}
printf("\n%s",fraction_bin);
free(integer_bin);
integer_bin=(char*)malloc(9*sizeof(char));
strcpy(integer_bin,"00000000");
printf("integer_bin %s",integer_bin);
integer=127+size-1;
i=1;
while(integer>0){
remainder=fmod(integer,2);
integer=integer/2;
*(integer_bin+8-i)=(char)(remainder+48);
i++;
}
*(integer_bin+8-i)=(char)(integer+48);
*(integer_bin+8)='\0';
printf("\n\n%s %s %s",sign,integer_bin,fraction_bin);
strcpy(fp.exponent,integer_bin);
strcpy(fp.sign,sign);
strcpy(fp.fraction,fraction_bin);
free(integer_bin);
free(integer_str);
free(fraction_bin);
free(fraction_str);
free(sign);
free(pch);
}
int main()
{
struct floating_point fp=stringToFloatingPoint("108,53");
printf("\n\n%s %s %s",fp.sign,fp.exponent,fp.fraction);
}
一切正常,直到 strcpy 部分。printf("\n\n%s %s %s",sign,integer_bin,fraction_bin); 这个 printf 效果很好。我的字符串的大小等于结构中的大小。你可以看到我使用 malloc 分配了多少内存。我没有收到错误,但是当我在主要功能中打印值时,它们不正确。问题可能是什么?