Declaring a pointer of type char* in a structure. Is this the way?

Status
Not open for further replies.

miz_doodle

Beta member
Messages
1
Anyone here can help me to verify whether i declared the structure, Binary correctly? THis struct is to store a pointer of type char*, which will point to an array storing a binary number(this is an array of char) and an int recording the num of digits in the binary number(size of array).

typedef struct Binary
{
int n;
char* binaryPtr;

};


When i try to compile the following codes, it does not give any errors UNTIL i enter choice=2( print the binary number) it always gives the memory allocation error and points out at the line highlighted in red below. cud it be memory allocation or i have declared the "char* binaryPtr" or printBinary() is not defined correctly? thnks in advance!


void readBinary(Binary* bPtr);
void printBinary(const Binary* bPtr);
void printMenu(void);

int main()
{
int n;
Binary* bin=NULL;
int choice;
int i;

bin= (Binary*) malloc(sizeof(Binary));// allocate memory


while(1)
{
printMenu();

printf("Enter your selection:");
scanf("%d", &choice);

if(choice ==1)
{
//prompt for number of bits of binary number
printf("Enter n:");
scanf("%d", &n);
bin->n=n;

readBinary(bin);

}

if(choice ==2)
{

printBinary(bin);
}
if(choice ==3)//quit
{

break;
}
}

free(bin);//deallocate memory

return 0;

}

void readBinary(Binary* bPtr)
{
int i;

char array[MAXLENGTH];


Binary* bin= (Binary*) malloc(sizeof(Binary));// allocate memory


printf("Enter a binary number:");

for(i=0;i<bPtr->n;i++)

scanf(" %c", &(array)); //reads the binary number in array of chars

bin->binPtr=array;

free(bin);


}

void printBinary(const Binary* bPtr)
{
int i;

for(i=0;i<bPtr->n;i++)
printf("%c", bPtr->binaryPtr);

}
 
Status
Not open for further replies.
Back
Top Bottom