F
Fatted
I'm trying to learn how to create arrays dynamically. But its just not
happening. Have a look at code below and point and laugh where
appropriate...
First part of program, I'm using an array of pointers, which seems to go
ok. I want to then take it one step further and dynamically create the
array (pointers to pointers). I try to print out the data again,
retrieve the first 3 values (probably by luck), then maybe a pointer
value, and then a seg fault. Doing something wrong, can't see what...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int * num[5];
int ** digit;
int ** place;
int i;
printf("before assignments\n");
for(i = 0; i < 5; i++)
{
if((num = malloc(sizeof(int) )) == NULL)
{
perror("num malloc\n");
}
*num = i*3;
printf("%d\n",*num);
}
printf("Relooping through the array of pointers\n");
for(i = 0; i < 5; i++)
{
printf("%d\n",*num);
free(num);
}
printf("before pointer to pointer\n");
if((digit = malloc(sizeof(int *) )) == NULL)
{
perror("digit malloc\n");
}
if((place = malloc(sizeof(int **) )) == NULL)
{
perror("place malloc\n");
}
/* hang on to the location of the start of digit */
place = digit;
for(i = 0; i < 5; i++)
{
if((*digit = malloc(sizeof(int) )) == NULL)
{
perror("*digit malloc\n");
}
**digit = i*5;
printf("%d\n",**digit);
*digit++;
}
printf("loop thru digit again\n");
for(i = 0; i < 5; i++)
{
printf("%d\n",**place);
free(*place);
*place++;
}
/*
for(i = 0; i < 5; i++)
{
printf("%d\n",*place);
free(place);
}
*/
free(place);
return(0);
}
happening. Have a look at code below and point and laugh where
appropriate...
First part of program, I'm using an array of pointers, which seems to go
ok. I want to then take it one step further and dynamically create the
array (pointers to pointers). I try to print out the data again,
retrieve the first 3 values (probably by luck), then maybe a pointer
value, and then a seg fault. Doing something wrong, can't see what...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int * num[5];
int ** digit;
int ** place;
int i;
printf("before assignments\n");
for(i = 0; i < 5; i++)
{
if((num = malloc(sizeof(int) )) == NULL)
{
perror("num malloc\n");
}
*num = i*3;
printf("%d\n",*num);
}
printf("Relooping through the array of pointers\n");
for(i = 0; i < 5; i++)
{
printf("%d\n",*num);
free(num);
}
printf("before pointer to pointer\n");
if((digit = malloc(sizeof(int *) )) == NULL)
{
perror("digit malloc\n");
}
if((place = malloc(sizeof(int **) )) == NULL)
{
perror("place malloc\n");
}
/* hang on to the location of the start of digit */
place = digit;
for(i = 0; i < 5; i++)
{
if((*digit = malloc(sizeof(int) )) == NULL)
{
perror("*digit malloc\n");
}
**digit = i*5;
printf("%d\n",**digit);
*digit++;
}
printf("loop thru digit again\n");
for(i = 0; i < 5; i++)
{
printf("%d\n",**place);
free(*place);
*place++;
}
/*
for(i = 0; i < 5; i++)
{
printf("%d\n",*place);
free(place);
}
*/
free(place);
return(0);
}