473,888 Members | 1,583 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array of pointers

60 New Member
Hello:

I've been working on an assignment and I have hit a stumbling block pertaining to an array of pointers.

If I am correct in my assumptions, the array

Expand|Select|Wrap|Line Numbers
  1. struct animal* zoo[4]
should have its address passed to a function when calling it like this:

Expand|Select|Wrap|Line Numbers
  1. somefunc(zoo);
Once I am in somefunc, if I call the line of code:

Expand|Select|Wrap|Line Numbers
  1. free(zoo[0]);
  2. zoo[0] = 0;
causes the program to crash. Specifically the error is commented out on line 261 of hw2************ ***Driver.c below. Thank you to anyone who can enlighten me on why this seemingly innoculous line is causing the program to crash.

-fauxanadu

hw2************ ***Constants.c
Expand|Select|Wrap|Line Numbers
  1. /******************************************************************************
  2. *  PROGRAMMER        : ***************                                        *
  3. *  LANGUAGE          : C                                                       *
  4. *  CLASS             : CSE 1320-002, Fall 2007                                 *
  5. *  COMPILER          : gcc                                                     *
  6. *  OPERATING SYSTEM  : Unix                                                    *
  7. *  PLATFORM          : omega                                                   *
  8. *  COURSE            : Intermmediate Programming                               *
  9. *  ASSIGNMENT        : Homework 1                                              *
  10. *  ASSIGNED          : 27 September 2007                                       *
  11. *  DUE               : 16 October   2007                                       *
  12. *  FILED AS          : hw2***************Constants.c                           *
  13. *  FILES USED        : hw2***************Constants.c                           *
  14. *                    : hw2***************Driver.c                              *
  15. *  CONCEPTS          : Structures, dynamic memory (de)allocation, file I/O     *
  16. *                    : Command Line Arguments                                  *
  17. *  WEIGHT            : 10% of Final Grade                                      *
  18. *  PURPOSE           : Include required system files                           *
  19. *                      Define global constants                                 *
  20. *                      Prototype Functions                                     *
  21. *****************************************************************************/
  22. // System Files
  23. #include <stdlib.h>
  24. #include <stdio.h>
  25.  
  26. // Constants
  27. #define CMD_ARGS 2
  28. #define CMD_CHAR '*'
  29. #define CMD_INDEX 0
  30. #define CTRL_INDEX 1
  31. #define CTRL_END 'E'
  32. #define CTRL_FEED 'f'
  33. #define CTRL_PRCH 'p'
  34. #define CTRL_TRAN 't'
  35. #define DISP_FLOAT 4
  36. #define DISP_INT 4
  37. #define DISP_NAME 11
  38. #define DISP_PREC 1
  39. #define DISP_STRING 7
  40. #define ERR_NONE 0
  41. #define ERR_BAD_ARGS 1
  42. #define ERR_MISSING_FILE 2
  43. #define ERR_MALFORMED 3
  44. #define FALSE 0
  45. #define FILE_INDEX 1
  46. #define LINE_SIZE 51
  47. #define LOW_INDEX 0
  48. #define NULLS '\0'
  49. #define NULLP 0
  50. #define STRING_LARGE 20
  51. #define STRING_SMALL 10
  52. #define STARTI 0
  53. #define STARTT 0
  54. #define TRUE 1
  55. #define ZEROF 0.0
  56. #define ZEROI 0
  57. #define ZOO_SIZE 4
  58.  
  59. // Objects
  60. struct Animal
  61. {
  62.   char color[STRING_LARGE];
  63.   char name[STRING_LARGE];
  64.   char species[STRING_LARGE];
  65.   double food;
  66.   double water;
  67.   int age;
  68.   int id;
  69.   int weight;
  70. };
  71.  
  72. // Function Prototypes
  73. void purchase(FILE**, struct Animal*[], char[]);
  74. void maintain(FILE**, struct Animal*[], char[]);
  75. void report(struct Animal*[]);
  76. void transfer(FILE**, struct Animal*[], char[]);
  77.  
hw2************ ***Driver.c
Expand|Select|Wrap|Line Numbers
  1. /*****************************************************************************
  2. *  PROGRAMMER        : ****************                                        *
  3. *  LANGUAGE          : C                                                       *
  4. *  CLASS             : CSE 1320-002, Fall 2007                                 *
  5. *  COMPILER          : gcc                                                     *
  6. *  OPERATING SYSTEM  : Unix                                                    *
  7. *  PLATFORM          : omega                                                   *
  8. *  COURSE            : Intermmediate Programming                               *
  9. *  ASSIGNMENT        : Homework 1                                              *
  10. *  ASSIGNED          : 27 September 2007                                       *
  11. *  DUE               : 16 October   2007                                       *
  12. *  FILED AS          : hw2***************Driver.c                              *
  13. *  FILES USED        : hw2***************Constants.c                           *
  14. *                    : hw2***************Driver.c                              *
  15. *  CONCEPTS          : Structures, dynamic memory (de)allocation, file I/O     *
  16. *                    : Command Line Arguments                                  *
  17. *  WEIGHT            : 10% of Final Grade                                      *
  18. *  PURPOSE           : Define Functions                                        *
  19. *****************************************************************************/
  20.  
  21. #include "hw2****************Constants.c"
  22.  
  23. int main(int argc, char* argv[])
  24. {
  25.   //Variable Declaration
  26.   char lineIn[LINE_SIZE] = {NULLS};
  27.   FILE* input = {ZEROI};
  28.   struct Animal* zoo[ZOO_SIZE] = {NULLP};
  29.  
  30.   // Checks that there were 2 arguments passed at the command line
  31.   if(argc != CMD_ARGS)
  32.   {
  33.     printf("\nError %d", ERR_BAD_ARGS);
  34.     printf("\nThe proper syntax is:");
  35.     printf("\n>executable.exe file.dat\n");
  36.     exit(ERR_BAD_ARGS);
  37.   }
  38.  
  39.   // Opens the file and checks for success
  40.   input = fopen(argv[FILE_INDEX], "r");
  41.   if (!input)
  42.   {
  43.     printf("\nError %d", ERR_MISSING_FILE);
  44.     printf("\nThe file %s could not be opened. \n", argv[FILE_INDEX]);
  45.     exit(ERR_MISSING_FILE);
  46.   }
  47.  
  48.   // Gets a line of input and determines which function to call
  49.   fgets(lineIn, LINE_SIZE - 1, input);
  50.   while(!(lineIn[CMD_INDEX] == CMD_CHAR & lineIn[CTRL_INDEX] == CTRL_END))
  51.   {
  52.     printf("\n");
  53.     if(lineIn[CMD_INDEX] == CMD_CHAR)
  54.     {
  55.       switch(lineIn[CTRL_INDEX])
  56.       {
  57.         case CTRL_FEED:
  58.           maintain(&input, zoo, lineIn);
  59.           break;
  60.         case CTRL_PRCH:
  61.           purchase(&input, zoo, lineIn);
  62.           break;
  63.         case CTRL_TRAN:
  64.           transfer(&input, zoo, lineIn);
  65.           break;
  66.         default:
  67.           printf("\nError %d", ERR_MALFORMED);
  68.           printf("\nThe input file is malformed.");
  69.           printf("\nPlease consult the documentation\n");
  70.           exit(ERR_MALFORMED);
  71.       }
  72.     }
  73.     report(zoo);
  74.   }
  75.  
  76.   return ERR_NONE;
  77. }
  78.  
  79. void purchase(FILE** input, struct Animal* zoo[], char lineIn[])
  80. {
  81.   //Variable Declaration
  82.   int i = ZEROI;
  83.   char a[STRING_SMALL], b[STRING_SMALL], c[STRING_SMALL],
  84.        d[STRING_SMALL], e[STRING_SMALL], f[STRING_SMALL],
  85.        g[STRING_SMALL];
  86.  
  87.   //Gets line of input
  88.   fgets(lineIn, LINE_SIZE - 1, *input);
  89.  
  90.   //Exit Condition  
  91.   if(lineIn[CMD_INDEX] == CMD_CHAR)
  92.   {
  93.     return;
  94.   }
  95.  
  96.   for(i = STARTI; i < ZOO_SIZE; i++)
  97.   {
  98.     if (zoo[i] == NULLP)
  99.     {
  100.       zoo[i] = (struct Animal*)malloc(1 * sizeof(struct Animal));
  101.       sscanf(lineIn, "%s%s%s%s%s%s%s", a, b, c, d, e, f, g);
  102.       strcpy(zoo[i]->species, a);
  103.       strcpy(zoo[i]->name, b);
  104.       if(!(isdigit(c[LOW_INDEX])))
  105.       {
  106.         strcat(zoo[i]->name, " ");
  107.         strcat(zoo[i]->name, c);
  108.         zoo[i]->age = atoi(d);
  109.         zoo[i]->weight = atoi(e);
  110.         zoo[i]->id = atoi(f);
  111.         strcpy(zoo[i]->color, g);
  112.       }
  113.       else
  114.       {
  115.         zoo[i]->age = atoi(c);
  116.         zoo[i]->weight = atoi(d);
  117.         zoo[i]->id = atoi(e);
  118.         strcpy(zoo[i]->color, f);
  119.       }
  120.       zoo[i]->food = ZEROF;
  121.       zoo[i]->water = ZEROF;
  122.       printf("Purchasing: %s\n", zoo[i]->name);
  123.       break;
  124.     }
  125.   }
  126.  
  127.   //Makes sure the for loop exited early, if not, inform user
  128.   if(i >= ZOO_SIZE)
  129.   {
  130.     sscanf(lineIn, "%s%s%s%s%s%s%s", a, b, c, d, e, f, g);
  131.     printf("Purchase failed: %s ", b);
  132.     if(!(isdigit(c[LOW_INDEX])))
  133.     {
  134.       printf("%s ", c);
  135.     }
  136.     printf("\n");
  137.   }
  138.  
  139.   //Recurses and then returns
  140.   purchase(input, zoo, lineIn);
  141.   return;
  142. }
  143.  
  144. void maintain(FILE** input, struct Animal* zoo[], char lineIn[])
  145. {
  146.   //Variable Declaration
  147.   int i = ZEROI;
  148.   char a[STRING_LARGE], b[STRING_SMALL], c[STRING_SMALL], d[STRING_SMALL];
  149.  
  150.   //Gets line of input
  151.   fgets(lineIn, LINE_SIZE - 1, *input);
  152.  
  153.   //Exit Condition  
  154.   if(lineIn[CMD_INDEX] == CMD_CHAR)
  155.   {
  156.     return;
  157.   }
  158.  
  159.   //Separates out the desired data
  160.   sscanf(lineIn, "%s%s%s%s", a, b, c, d);
  161.   if(!(isdigit(b[LOW_INDEX])))
  162.   {
  163.     strcat(a, " ");
  164.     strcat(a, b);
  165.   }
  166.  
  167.   for(i = STARTI; i < ZOO_SIZE; i++)
  168.   {
  169.     if(!(strcmp(zoo[i]->name, a)))
  170.     {
  171.       printf("Maintaining: %s\n", zoo[i]->name);
  172.       if(isdigit(b[LOW_INDEX]))
  173.       {
  174.         zoo[i]->food = atof(b);
  175.         zoo[i]->water = atof(c);
  176.       }
  177.       else
  178.       {
  179.         zoo[i]->food = atof(c);
  180.         zoo[i]->water = atof(d);
  181.       }
  182.     }
  183.   }
  184.  
  185.   //Recurses and then returns
  186.   maintain(input, zoo, lineIn);
  187.   return;
  188. }
  189.  
  190. void report(struct Animal* zoo[])
  191. {
  192.   //Variable Declaration
  193.   static int headerPrinted = FALSE;
  194.   static int i = ZEROI;
  195.  
  196.   //Exit condition
  197.   if(i >= ZOO_SIZE)
  198.   {
  199.     return;
  200.   }
  201.  
  202.   //If the header has not been printed, prints it
  203.   if(headerPrinted == FALSE)
  204.   {
  205.     printf("----+------------+--------+-----+-------+--------+------+------\n");
  206.     printf("ID  |Name        |Species |Age  |Weight |Color   |Food  |Water \n");
  207.     printf("----+------------+--------+-----+-------+--------+------+------\n");
  208.     headerPrinted = TRUE;
  209.   }
  210.   if(zoo[i])
  211.   {  //Prints out the current animals information
  212.     printf("%-*d|%-*s |%-*s |%*d |  %*d |%-*s | %*.*f | %*.*f \n", 
  213.                                           DISP_INT, zoo[i]->id,
  214.                                           DISP_NAME, zoo[i]->name,
  215.                                           DISP_STRING, zoo[i]->species,
  216.                                           DISP_INT, zoo[i]->age,
  217.                                           DISP_INT, zoo[i]->weight,
  218.                                           DISP_STRING, zoo[i]->color,
  219.                                           DISP_FLOAT, DISP_PREC, zoo[i]->food,
  220.                                           DISP_FLOAT, DISP_PREC, zoo[i]->water);
  221.   }
  222.  
  223.   //Recurses and resets variables for next print
  224.   i++;
  225.   report(zoo);
  226.   headerPrinted = FALSE;
  227.   i = ZEROI;  
  228.   return;
  229. }
  230.  
  231.  
  232.  
  233.  
  234.  
  235.  
  236. void transfer(FILE** input, struct Animal* zoo[], char lineIn[])
  237. {
  238.   //Variable Declaration
  239.   int i = ZEROI;
  240.   char a[STRING_SMALL];
  241.  
  242.   //Gets line of input
  243.   fgets(lineIn, LINE_SIZE - 1, *input);
  244.  
  245.   //Exit Condition  
  246.   if(lineIn[CMD_INDEX] == CMD_CHAR)
  247.   {
  248.     return;
  249.   }
  250.  
  251.   //Separates out the desired information
  252.   sscanf(lineIn, "%s%s%s%s%s%s%s", a);
  253.  
  254.   //Checks each element of the zoo to see if it matches
  255.   for(i = ZEROI; i < ZOO_SIZE; i++)
  256.   {
  257.     if(!(strcmp(zoo[i]->name, a)))
  258.     {
  259.       printf("Transfering: %s\n", zoo[i]->name);
  260.       free((struct Animal*)zoo[i]);
  261.       //zoo[i] = (struct Animal*)NULLP;
  262.       break;
  263.     }
  264.   }
  265.  
  266.   if(i >= ZOO_SIZE)
  267.   {
  268.     printf("Transfer Failed: %s", lineIn);
  269.   }
  270.  
  271.   //Recurses and then returns
  272.   transfer(input, zoo, lineIn);    
  273.   return;
  274. }
Oct 15 '07 #1
8 1318
mattmao
121 New Member
Hi.

I've no time so I skip your assignment requirements:(

But you can see my sample code for the array of structs:

Expand|Select|Wrap|Line Numbers
  1.   #include <stdio.h>
  2.  
  3. struct rectangle
  4. {
  5.    int width, height;
  6. };
  7.  
  8. int main()
  9. {
  10.    struct rectangle recArray[10];
  11.    int i;
  12.  
  13.    for(i=0; i<10; i++)
  14.       recArray[i].width = i;
  15.  
  16.    for(i=0; i<10; i++)
  17.       printf("%d ", recArray[i].width);
  18.  
  19.    return;
  20.  
  21. }
And the result:
Expand|Select|Wrap|Line Numbers
  1. charlie$ gcc structarray.c
  2. charlie$ ./a.out          
  3. 0 1 2 3 4 5 6 7 8 9 charlie$ 
I think this would help you to access the "properties " inside each of the struct "elements". ..
Oct 15 '07 #2
fauxanadu
60 New Member
I have to use an array of dynamically allocated pointers. I can't figure out why:
zoo[0] = 0;

is causing the program to crash. zoo is defined as
struct animal* zoo[4];

and is sent to a function via
somefunc(zoo);

Once in somefunc, the assignment mentioned at the top of this post causes the program to crash.
Oct 15 '07 #3
mattmao
121 New Member
Hi

zoo[0] is the "address to first struct element", you cannot assign an int to that address...

I would suggest you take more time reading the lecture notes for better understanding about this god damned issue...

I am doing my assignment2, which requires a linked list of linked lists...
Oct 15 '07 #4
fauxanadu
60 New Member
I have read the lecture notes quite throughly and this part of the program is actually a direct copy of what the professor has in his notes. I cannot figure out why it will not work in this context.
Oct 15 '07 #5
mattmao
121 New Member
Well, as for me I would use this:

struct rectangle recArray[10];

It means an array of struct elements, each of which could be accessed by using recArray[i].

I don't know why your pro would use struct somecClass *array[10];

I don't know how to do this job in thay way:(
Oct 15 '07 #6
RRick
463 Recognized Expert Contributor
Your problem is a one of initialization. You are trying to free something that is pointed to by an uninitialized pointer.

Expand|Select|Wrap|Line Numbers
  1. struct animal * zoo[4];
This code will create an array of 4 pointers to a struct animal. This does not set any of the pointer values in zoo, so using zoo[0] will access something with a bad pointer.

Later on you try to free zoo[0] and this is probably what is causing your program to blow up. If you want to free something, the pointer has to be either NULL or a valid pointer value (i.e, created by malloc,etc.).


One solution is to initialize zoo when you declare it.
Expand|Select|Wrap|Line Numbers
  1. struct animal * zoo[4] = { NULL, NULL, NULL, NULL};
should fix the problem.
Oct 15 '07 #7
fauxanadu
60 New Member
It is actually initialized to null. (on line 28.):
28. struct Animal* zoo[ZOO_SIZE] = {NULLP};

With NULLP being equal to 0.

In the main function I can set zoo[0] = 0; just fine and it works. Once I pass the address of zoo to a function, inside that function the exact same assignment stops working. That is the problem. I need to know why as I cannot figure it out. I've been working on this problem for three nights intermittantly and it just won't work no matter what I do.
Oct 15 '07 #8
RRick
463 Recognized Expert Contributor
There are over 300 lines of code, an unknown data file, and even recursive calls. This can get complicated, very quickly.

You need to narrow down the scope of the problem and figure out the location where the problem occurs. What is needed to reproduce this problem? We also need values for zoo before and after the problem area is called.
Oct 15 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

14
8492
by: dam_fool_2003 | last post by:
Friends, cannot we malloc a array? So, I tried the following code: int main(void) { unsigned int y={1,3,6},i,j; for(i=0;i<3;i++) printf("before =%d\n",y); *y = 7; /* 1*/
20
2986
by: fix | last post by:
Hi all, I feel unclear about what my code is doing, although it works but I am not sure if there is any possible bug, please help me to verify it. This is a trie node (just similar to tree nodes) struct, I am storing an array of 27 pointers and a void pointer that can point to anything. typedef struct trieNode { struct trieNode *children; // The children nodes void *obj; // The object stored } TrieNode;
19
14539
by: gaga | last post by:
I can't seem to get this to work: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *names; char **np;
204
13171
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
2
2136
by: Simon Morgan | last post by:
I hope this isn't OT, I looked for a newsgroup dealing purely with algorithms but none were to be found and seeing as I'm trying to implement this in C I thought this would be the best place. I have an array of structs containing data which I'd like to output ordered based on the value of a single member. I was wondering if there is a relatively simple way of doing this without actually modifying the structure of the array? I had a...
5
3140
by: Paminu | last post by:
Why make an array of pointers to structs, when it is possible to just make an array of structs? I have this struct: struct test { int a; int b;
17
7266
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need to show the array data to the end user. Can I do that? How?
2
2990
by: StevenChiasson | last post by:
For the record, not a student, just someone attempting to learn C++. Anyway, the problem I'm having right now is the member function detAddress, of object controller. This is more or less, your standard dynamic address book program. Adding, and listing work just fine. However, deleting, editing and viewing relies on member function retAddress. This function returns an array of pointers that are pointing to created objects. In action, all it...
17
2342
by: Ben Bacarisse | last post by:
candide <toto@free.frwrites: These two statements are very different. The first one is just wrong and I am pretty sure you did not mean to suggest that. There is no object in C that is the same as its address. The second one simply depends on a term that is not well-defined. Most people consider the type to be an important part of the notion of
33
7201
by: Adam Chapman | last post by:
Hi, Im trying to migrate from programming in Matlab over to C. Im trying to make a simple function to multiply one matrix by the other. I've realised that C can't determine the size of a 2d array, so im inputting the dimensions of those myself. The problem is that the output array (C=A*B) has as many rows as A and as many columns as B. I would think of initialising C with:
0
9800
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10777
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10882
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10438
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9597
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7990
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7148
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5817
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3251
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.