-2

What wrong with this code i see no compilation error. I want to make an array of structures of type pointer to structure. Then i want to assign x and y coordinates and at the end i want to print all the coordinates. I did (*pp).x at places and pp->x at other places. Coz both are one and the same things whats wrong. Please let me know.

#include <stdio.h>
#include <conio.h>
#define MAX_STRUCT 10

struct point{
    int x; 
    int y; 
};

void PrintIt(int x, int y);
main()
{
struct point *pp[MAX_STRUCT]; 

printf("Enter how many coordinates you want to input: ");
int count=0, n; 
scanf("%d", &n);

while(count<n){
printf("\nEnter the X & Y coordinate of the point: ");
int i,j; 
scanf("%d%d", &i, &j);

(*pp[count]).x=i; /* or we can do this : pp[count] -> x same thing
(*pp[count]).y=j;   // or we can do this : pp[count] -> y same thing


count++;
}  
PrintIt(pp[count]->x, pp[count]->y);

return 0;
}

void PrintIt(int x, int y)
{
    printf("\n(%d,%d)", x, y); 
}
HELP PLZ
  • 41
  • 1
  • 9

1 Answers1

1

You need to dynamically allocate memory for pp:

#include <stdlib.h>
struct point *pp = malloc(MAX_STRUCT * sizeof(*pp)); // sizeof(struct point) would work too

Or, don't make them pointers:

struct point pp[MAX_STRUCT];
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
  • i used this by replacing the first line :::::struct point *pp[MAX_STRUCT]= (struct point *)malloc(MAX_STRUCT * sizeof(struct point *)); :::::::::::::::::::::::but i get an compiler error can you tell me the possible fix in this code? – HELP PLZ Aug 10 '14 at 00:27
  • you didn't typecasted it? – HELP PLZ Aug 10 '14 at 00:28
  • See this thread on typecasting `malloc`'s `return`: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc. – Fiddling Bits Aug 10 '14 at 00:37
  • You need to use either `sizeof(struct point)` or `sizeof(*pp)`. – Fiddling Bits Aug 10 '14 at 00:38
  • its still giving me an error :::::::::::::::::::::D:\C Programming\struct.c In function 'main': 15 6 D:\C Programming\struct.c [Warning] incompatible implicit declaration of built-in function 'malloc' [enabled by default] 15 4 D:\C Programming\struct.c [Error] incompatible types when assigning to type 'struct point *[10]' from type 'void *' – HELP PLZ Aug 10 '14 at 00:44
  • You need to `#include `. You must be using the C++ compiler if it's complaining about not typecasting. – Fiddling Bits Aug 10 '14 at 00:46