// what\'s wrong with the following code? // <<<START CODE>>> #include<stdio.h>
ID: 3630223 • Letter: #
Question
// what's wrong with the following code?// <<<START CODE>>>
#include<stdio.h>
#include<stdlib.h>
#define K 4
struct b {
int fee; int fie; int foe; int fum; } ;
int main(int argc, char * argv[]) {
int * iap ; // integer array pointer
struct b * sbp ; // struct b pointer
int i ;
iap = (int *) malloc( K*sizeof(int) ) ;
for ( i=0; i<K; i++ ) iap[i] = ( i+1 ) ;
sbp = (struct b *) iap ;
printf("%d %d %d %d ",
sbp->fee, sbp->fie, sbp->foe, sbp->fum ) ;
return 0 ;
}
// <<<END CODE>>>
Explanation / Answer
This compiles and runs under Linux with output: 1 2 3 4 Are you getting an error that you need help with or are asking a hypothetical coding convention question? If you're looking for the second: It's not recommended to allocate structures like this, but in this case it works fine because the structure is uniformly distributed. The code would break if someone changed the structure later without knowing about the malloc assumption/dependency. Another problem is the lack of release of heap space with the "free" function call.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.