Skip to content

Instantly share code, notes, and snippets.

@RobinStamer
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save RobinStamer/37e80a4c682205affda4 to your computer and use it in GitHub Desktop.

Select an option

Save RobinStamer/37e80a4c682205affda4 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct stack
{
char *arr;//array of chars
int size;
int top;
}stack;
void grow(stack *);
void stackInit(stack *);
int main(int argc, char const *argv[])
{
stack st1;
stackInit(&st1);
st1.arr[0] = 'H';
st1.arr[1] = 'i';
st1.arr[2] = '!';
st1.arr[3] = 0;
printf("%d: %s\n", st1.size, st1.arr);
grow(&st1);
printf("%d: %s\n", st1.size, st1.arr);
return 0;
}
void stackInit(stack *s) {
s->size = 4;
s->top = 0;
s->arr = malloc(4 * sizeof(char));
}
void grow(stack *pst)
{
char *temp;//Create temp array
temp = (char *) malloc (((pst->size) + 1) * sizeof(char));//Allocate the correct amount of space for the temp array.
int i;
if (NULL == temp) {
return;
}
for (i=0;i<pst->size;i++)//Put all values from the old array into the temp array.
(temp)[i]=(pst->arr)[i];
free(pst->arr);//Free the old array's memory.
pst->arr=temp;//Point the old array at the adress of the new array.
pst->size=(pst->size)+1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment