Lambda said:
I'd like to create separate character pointers,
pass them to a function to assign each one different value,
and assign the pointers to an array.
But when I try:
#include <stdio.h>
#include <string.h>
int main(void)
{
int i;
for (i = 0; i < 5; ++i)
{
char *str = "test";
printf("%p:%s\n", str, str);
}
return 0;
}
All the pointers refer to the same address.
When the 'char *str = "test"' is run, no new pointer is created?
A new pointer object is created each time, though on many
implementations that new pointer object is likely to be created in
exactly the same location. The key problem isn't the pointer object,
it's the pointer value that it's initialized with. When you write a
string literal such as "test" in contexts like this one, what happens is
that an unnamed array of 5 characters is created and filled in with 't',
'e', 's', 't', and '\0'. The string literal is treated as a pointer to
that array. Therefore, every time you go through the loop, you
initialize your pointer object with a pointer value that points at the
same unnamed array.
The right way to fix this depends very much on what it is that you're
trying to do. The simplest approach that matches your description would
be as follows:
#include <stdio.h>
int main(void)
{
char str1[] = "test";
char str2[] = "test";
char str3[] = "test";
char str4[] = "test";
char str5[] = "test";
char *array[5] = {str1, str2, str3, str4, str5};
int i;
for(i=0; i<5; ++i)
printf("%p:%s\n", array
, array);
// Use array.
return 0;
}
Note that in this case the string literals are used to initialize an
array, not a pointer in an array. In this case, no unnamed array is
created; instead, each definition creates a separate array and
initializes that array
While the above code matches your description, I doubt that it's what
you really want. The following more complicated case is probably closer
to what you're looking for:
#include <stdio.h>
#include <stdlib.h>
#define STRINGS 5
int main(void)
{
char *array[STRINGS];
int i;
for(i=0; i<STRINGS; i++)
{
array = malloc(5);
if(array)
{
strcpy(array, "test");
printf("%p:%s\n", array, array);
}
else
{
printf("%p: failed allocation\n", array);
}
}
for(i=0; i<STRINGS; i++)
free(array);
return 0;
}