Tuesday, November 8, 2011

Returning memory from a function

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

char *get_street_address(void); /*function prototype*/

int main(void) {

char *street_address =  NULL;

street_address =  get_street_address();

/*Check if the above state is successful if not the program is terminated*/
assert(street_address != NULL):

printf("The entered street address was: %s \n",  street_address);

/*Return the memory block to the pool*/
free(street_address);

return 0;
}

/*Implement the function get_street_address(void)*/
char *get_street_address(void) {

/*Assign a memory of 150 characters to the "input" pointer*/
char *user_input = malloc(150);

/*Check if the memory assignment is successful*/
if (user_input == NULL) {
   printf("Unable to assign memory!\n");
   return NULL;
}

/*Ask for user_input*/
printf("Enter your street address: ");
scanf("%149s", user_input);

getchar();

return user_input;
}

No comments:

Post a Comment

Mounting USB drives in Windows Subsystem for Linux

Windows Subsystem for Linux can use (mount): SD card USB drives CD drives (CDFS) Network drives UNC paths Local storage / drives Drives form...