Segmentation Fault when calling member of a struct
<p>sorry if this has been asked a million times before, but I think I have a problem understanding how strings (char arrays) work in C.</p>

<p>In my program, I have a "stack" struct, which looks like this (in stack.h):</p>

<pre><code>struct stack_t {
/* Stack-Datentyp */
/* Stacks have a head-node, a length, and a name.
Stacks are filled with links (nodes) that are defined below. These links have
a generic data pointer and a pointer to the next link */
link head;                      
unsigned int length;            
char *name;                     //stack name
};

typedef struct stack_t *stack;
</code></pre>

<p>in my main.c, I call a function called "stack_new" which seems to work properly, since all the printf-calls work:</p>

<pre><code>stack stack_new(char *stackname) {
  /* creates a new, empty stack */
stack st = (stack)(malloc(sizeof(stack)));
if (st == NULL) {
fprintf(stderr, "Error: Memory for Stack could not be allocated!\n");
return NULL;
}
st-&gt;head = NULL;
printf("head works.\n");
st-&gt;length = 0;
printf("length works.\n");
st-&gt;name = stackname;
printf("stackname works.\n");
return st;
}
</code></pre>

<p>Now, when I call this function in main.c, I get a seg fault. Here is the call:</p>

<pre><code>if (strcmp(input,"newstack") == 0) {
    printf("Please enter stackname:\n");
    scanf("%s", &amp;stackname);
    printf("Debug: Input works.\n");
    stacklist[NumberOfStacks] = stack_new(stackname);
    printf("stack created works-\n");
    NumberOfStacks++;
    printf("A new stack with the name '%s' was created!\nIt is number %d in stack list.", stacklist[NumberOfStacks]-&gt;name, NumberOfStacks);
    continue;
}
</code></pre>

<p>The seg fault happens when I try to print the member name of the struct stacklist[NumberOfStacks] points to. What am I doing wrong here?</p>

<p>I also get a bunch of warnings that tell me about how my scanf for stackname expects a different type:</p>

<blockquote>
  <p>warning: format ‘%s’ expects argument of type ‘char <em>’, but argument 2 has type ‘char (</em>)[50]’ [-Wformat=]
       scanf("%s", &amp;stackname);</p>
</blockquote>

<p>Other warnings I get tell me that I am not typecasting from my void-pointer I use for data storage in the stack nodes, but I don't think that this is relevant to my problem here.</p>

<p>Thank you for your help!</p>

<p>Edit:
The problem was that I incremented NumberOfStacks before using it as index for printing the member of a struct saved in the array.</p>

<pre><code>NumberOfStacks++;
    printf("A new stack with the name '%s' was created!\nIt is      number %d in stack list.", stacklist[NumberOfStacks]-&gt;name, NumberOfStacks);
</code></pre>

<p>This part of the program works fine now, thanks!</p>