2

Trying to implement below code for some assignment but getting an error for malloc array generation "[Error] conflicting types for 'stack'" Any Help ?? Thanks in Advance.

#include<stdio.h>
   #include<stdlib.h>

    struct treenode
    {
        char info;
        struct treenode *firstchild;
        struct treenode *next;
        int flag;
    };

    typedef struct treenode *NODEPTR;
    NODEPTR *stack;
    // Trying to create array here
    stack=(NODEPTR*)malloc(sizeof(NODEPTR)*20);


    int main()
    {
        printf("YO\n");
        return 0;
    }

EDIT :


I can't move it to main , as i have to access the stack globally in different functions. because Stack array gets destroyed when it go to another function. check here http://ideone.com/5wpZsp ,


When i give static declaration globally it works smoothly, here : http://ideone.com/3vx9fz

mkkhedawat
  • 1,687
  • 2
  • 17
  • 34

4 Answers4

2

You can not call assignment operations at global scope. Try malloc operation in main() instead.

And the type of stack is not a pointer but pointer to pointer. Are you sure about it's declaration ?

Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • Ok. You have to allocate 20 `treenode`'s in the memory locations you have to just allocated. And remember to free all of them. – Mahesh Aug 27 '13 at 02:35
  • I can't move it to main , as i have to access the stack globally in different functions. – mkkhedawat Aug 27 '13 at 02:36
  • Keep the declaration globally but do the assignment in the `main`. You should be able to access `stack` in all the functions after it's declaration. – Mahesh Aug 27 '13 at 02:39
  • It shouldn't work even with the static declaration. I think you are getting confused between the typedef and what operator `[], *` does on pointers. Pay close attention to the warnings on the link you posted. You will understand the mistakes you are doing. – Mahesh Aug 27 '13 at 02:56
  • I am able to give static declaration globally but not dynamiclly – mkkhedawat Aug 27 '13 at 03:00
  • I don't want to give away the answer. But I wrote a program {http://coliru.stacked-crooked.com/view?id=11a0227e2b5259c88d417b107bf6a89f-7904cf83bb2b27db3f32fade22b567cc} to make you understand what mistake are you doing. Hope it helps ! – Mahesh Aug 27 '13 at 03:17
  • You didn't get my question actually, I know what ptr to ptr does. My question was dynamically declaration of array of ptrs to the ptrs. leave it . have peace & thanks for concern – mkkhedawat Aug 27 '13 at 03:22
1

Move your initialization of stack to inside of the main method.

EDIT An example showing how the malloc data can persist to other function calls even though malloc is called inside of main.

#include<stdio.h>
#include<stdlib.h>

struct treenode
{
    char info;
    struct treenode *firstchild;
    struct treenode *next;
    int flag;
};

typedef struct treenode *NODEPTR;
NODEPTR *stack;

void test_stack() 
{
    printf("%p\n", stack);
    printf("%d\n", stack[19]->flag);
}
int main()
{
    // Trying to create array here
    stack=(NODEPTR*)malloc(sizeof(NODEPTR)*20);
    stack[19] = (NODEPTR*)malloc(sizeof(struct treenode));
    stack[19]->flag = 42;
    test_stack();
    return 0;
}
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • 1
    If i declare malloc inside main , it will be destroyed if i go to other fucntion , i need to access it globally. – mkkhedawat Aug 27 '13 at 02:39
  • @Manish - No it won't, the memory will be allocated until you free it. You can use "stack" in another function. Check my edit for proof. – Louis Ricci Aug 27 '13 at 12:35
0
#include<stdio.h>
#include<stdlib.h>

struct treenode
    {
    char info;
    struct treenode *firstchild;
    struct treenode *next;
    int flag;
    };
    typedef struct treenode *NODEPTR;
    NODEPTR *stack;
   int main()
   {

    stack=malloc(sizeof(NODEPTR)*20);

    printf("YO\n");
    return 0;
  }

This will work.

allocate memory inside(malloc) your main.

There is no need to typecast out put of malloc. for further info see this post

EDIT :

In your comment you mentioned that memory will be destroyed when you move other function.

This is not true. Once you allocate memory using malloc it will not be destroyed until you call free().

So if you want to access the malloc'ed variable in other function pass the variable as argument to other function.

See this example program below

    #include<stdio.h>
#include<stdlib.h>
#include <string.h>
char *str;
void passMalloc(char **str);

int main()
{
    str = malloc(100 * sizeof(char));
    strcpy(str, "GoodMorning");
    printf("\nMain before pass : %s\n", str);
    passMalloc(&str);
    printf("Main after pass : %s\n\n", str);
    free(str);
    return 0;
}

void passMalloc(char **str)
{
    strcpy(*str, "GoodEvening");
    printf("Function Def : %s\n", *str);
}
Community
  • 1
  • 1
sujin
  • 2,813
  • 2
  • 21
  • 33
  • If i declare malloc inside main , it will be destroyed if i go to other fucntion , i need to access it globally. – mkkhedawat Aug 27 '13 at 02:39
  • pass the memory allocated variable from main to where you want to use the variable. When you done free the variable else you will meet memory leak.. – sujin Aug 27 '13 at 05:26
0

Step 1: Move the declaration of stack inside main. There's no reason it should be declared globally:

int main( void )
{
  NODEPTR *stack;
  ...

Step 2: Move the malloc call inside main (you cannot perform an assignment or a function call outside of a function).

Step 3: Drop the cast; it's unnecessary1 and just adds visual clutter.

Step 4: Use sizeof *stack as opposed to sizeof (NODEPTR) in the argument to malloc:

stack = malloc( sizeof *stack * 20 );

The result is the same, but this is easier to read, and avoids maintenance headaches if you ever change the type of stack.

Step 5: free your stack when you're done. Yeah, for this program it doesn't matter, but it's a good habit to get into.

So after all this, your code should read:

int main( void )
{
  NODEPTR *stack;
  stack = malloc( sizeof *stack * 20 );
  ...
  free( stack );
  return 0;
}

Stylistic nit: Hiding pointer types behind typedefs is bad juju IME. Pointer semantics are important, and if the programmer is ever expected to dereference an object of type NODEPTR (either explicitly, as (*node).info, or implicitly, as node->info), then it's usually best to declare that object using pointer declaration syntax, something like

typedef struct treenode Node;
Node *node;
Node **stack;
...
stack[i]->next = node->next;

etc. so the person using your types knows exactly how many levels of indirection are involved and can write their code accordingly (multiple indirection is not hard). If the type is meant to be truly opaque and never directly dereferenced, but just passed around to an API that handles all that, then hiding the pointerness of that type is okay. Otherwise, leave it exposed.

I tend not to typedef struct types for a similar reason, but I suspect I'm an outlier in that regard.

Ahd who broke the code formatter?!


1 - In C, that is; in C++, the cast is required, but if you're writing C++, you should be using new instead of malloc anyway.
John Bode
  • 119,563
  • 19
  • 122
  • 198