I am able to work with n instances of a structure in one mallocated area, but when I try to do the same thing with just character pointers, I get compiler errors about making integer from pointer without a cast. If I create a structure with just a character pointer in it, it works just fine... I am just not seeing something here!!!
This works:
Code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
struct items
{
unsigned int item_1;
unsigned int item_2;
};
struct items *items_ptr;
unsignedint i = 0;
unsignedint num = 0;
items_ptr = (struct items *) malloc (3 * sizeof(struct items));
if (items_ptr == NULL)
{
printf ("\nOut of memory - ending program.");
return1;
}
for (i = 0; i < 3; i++)
{
num = num + 1;
items_ptr[i].item_1 = num;
items_ptr[i].item_2 = num + 10;
}
for (i = 0; i < 3; i++)
{
printf ("%u %u \n", items_ptr[i].item_1, items_ptr[i].item_2);
}
free (items_ptr);
items_ptr = NULL;
return 0;
}
This DOES NOT work!
Code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char * items_ptr = NULL;
unsignedint i = 0;
char * one = "one";
char * two = "two";
char * three = "three";
items_ptr = (char *) malloc (3 * sizeof(char *));
if (items_ptr == NULL)
{
printf ("\nOut of memory - ending program.");
return1;
}
items_ptr[0] = (char *) one;
items_ptr[1] = two;
items_ptr[2] = three;
for (i = 0; i < 3; i++)
{
printf ("%s", items_ptr[i]);
}
free (items_ptr);
items_ptr = NULL;
return 0;
}