Computer Forums

Member Login

Remember Me? Sign Up! | Forgot Password
 
Slogan
 
Computer Forums > Programmers Lounge > Programming Discussions » Declaring a pointer of type char* in a structure. Is this the way?
Closed Thread
Old 04-20-2005, 02:44 PM   #1 (permalink)
 
Newb Techie

Join Date: Apr 2005

Posts: 1

miz_doodle

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

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[i])); //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[i]);

}
miz_doodle is offline  
 
Closed Thread

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On