arrays in c, and global variables

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vangogh
    New Member
    • Oct 2008
    • 1

    arrays in c, and global variables

    Hi, I am in the beginning phase of writing a stack in C. My problem is that when I try to initialize a stack, I want to be able to access the stack in other methods that I am going to write later. I was planning to creating a global variable and having that be the stack. However, when I try to do this, I get an "incomplete type" error. Also, in case its not clear, I am using a 2-d array and am having each element in the outer array be a string with a max length of SIZEW. Below is my code and any help is appreciated...


    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    int currentItems;
    int maxSize;
    int SIZEW=100;
    char *contents[];   //this is where I get the error; I think it is because I don't have a number inside the brackets.
                                  // I don't have a number inside the brackets because the size isn't known until StackInitialize is called.
    
    // Initialize an empty stack of a maximum of `size' elements.
    extern int StackInitialize(int size)
    {
        int ii;
        int jj;
        maxSize = size;
        char (*newContents)[SIZEW];    
        newContents = malloc(size*SIZEW);
    
        if (newContents == NULL)
        {
            return 1;
        }
        for (jj=0; jj<size; jj++)
        {
            for (ii=0; ii<1; ii++)
                newContents[jj][ii] = '\0';  //initialize the first character of each string element to the end-of-string character
        }
    
        contents = newContents;    //assign newContents, which is local, to contents, which is global
    
        return 0;
    }
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    You cannot create an array of unknown size. You can have a pointer. And then later point it to a dynamically allocated array.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      By any chance have you already written a linked list?

      You can implement a stack by adding to the end of the list (the push) and removing from the end (the pop) and looking at the end (the peek).

      Saves writing linked list code over again.

      Comment

      Working...