Dynamic Array Help

Reply

Join Date: Apr 2005
Posts: 31
Reputation: wsn is an unknown quantity at this point 
Solved Threads: 0
wsn wsn is offline Offline
Light Poster

Dynamic Array Help

 
0
  #1
Mar 3rd, 2008
Hi,

I can't figure out what is wrong with the code after trying to fix it for the last six hours i decided to give, please i need help =( big time
I'm trying to make a dynamic array of structures then printing the output of the elements but I haven't successed in either storing the elements of the structure in the array nor printing it

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define MAX 128
  5. typedef char String[MAX];
  6. typedef struct
  7. {
  8. String name;
  9. float s;
  10. } ST;
  11.  
  12. int main()
  13. {
  14. int size, Index;
  15. ST *p, *tmpa, *tmp;
  16. ST *dArray;
  17.  
  18. //create block
  19. //check return value of malloc
  20. tmpa= (ST *) malloc (1*sizeof(ST));
  21. if(tmpa==NULL)
  22. {
  23. printf("Error\n");
  24. exit(1);
  25. }
  26. else
  27. {p=tmpa;}
  28.  
  29. size=-1;
  30. printf("Enter information (\"exit\") to exit\n");
  31. printf("What is the name :");
  32. scanf("%s",(*p).name);
  33. if(strcmp((*p).name,"exit")==0)
  34. { exit(0); }
  35.  
  36. while(strcmp((*p).name,"exit")!=0)
  37. {
  38. printf("What is the size:");
  39. scanf("%f",&(*p).s);
  40. size++;
  41. (p[size]).name=(*p).name;
  42. p[size].s=(*p).s;
  43. tmp=(ST *)realloc(p,(size+1)*sizeof(ST));
  44. //check return value from tmp
  45. if (tmp==NULL)
  46. {
  47. printf("Error\n");
  48. exit(1);
  49. }
  50. else
  51. {p=tmp;}
  52. printf("Enter information (\"exit\") to exit\n");
  53. printf("What is the name :");
  54. scanf("%s",(*p).name);
  55.  
  56.  
  57. }//end of while loop
  58.  
  59. printf("The following new data:\n");
  60. for (Index = 0; Index <= size; Index++)
  61. {
  62. printf("%s has size %.2f \n",p[Index].name,p[Index].s);
  63. }
  64. free(p);
  65.  
  66. return 0;
  67. }
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC