Originally Posted by
Elysia
you really should explicitly specify the return type of all functions,
1. Dose that mean when declaring a function such as "main()" I should write it "int main()"?
2. Is "free()" only used in conjunction with"malloc(sizeof())"?
3. Can someone please explain these steps that were taken to fix the program?
Bugged code
Code:
#include <stdio.h>
#include <stdlib.h>
main()
{
int x,*p=malloc(sizeof(*p));
p=&x;
printf("Enter a value for x:");
scanf("%d",&x);
printf("this is the output of *p:%d\n",*p);
free(p);
getchar();
}
Fixed code
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
int *p = malloc(sizeof(*p));
printf("Enter a value for x:");
scanf("%d", &x);
*p = x; /* Assume that malloc() did not return a null pointer. */
printf("this is the output of *p: %d\n", *p);
free(p);
getchar();
return 0;
}
3a. "main()" was changed to "int main()"
3b. Notice she separated the variables during declaration, even though they are both integers. Is this necessary or just personal preference?
3c. "p=&x;" was changed to "*p=x;" also moved below scanf why?
3d. "return 0;" was used, I think I understand that one now.