This relates to C. I am having some trouble understanding how I can assign strings to char pointers within arrays from a function.
#include <stdio.h>
#include <string.h>
void function(char* array[]);
int main(void)
{
char* array[50];
function(array);
printf("array string 0: %s\n",array[0]);
printf("array string 1: %s\n",array[1]);
}
void function(char* array[])
{
char temp[] = "hello";
array[0] = temp;
array[1] = temp;
return;
}
Ideally, I would like the main printf function to return
array string 0: hello
array string 1: hello
But I'm having trouble understanding arrays of pointers, how these pass to functions and how to manipulate them in the function. If I declare a string like char temp[] = "string"
then how do I assign this to one of the main function array[i]
pointers? (assuming I have my jargon right)
char temp[] = "hello";
only creates a local, temporary array inside the function. So when the function exists, the array will be destroyed.
But with array[0] = temp;
you're making array[0]
point to the local array temp
.
After the function returns, temp
doesn't exist anymore. So accessing array[0]
which pointed to temp
will cause undefined behavior.
You could simply make temp
static, so it also exists outside the function:
static char temp[] = "hello";
Or, you could copy the "hello"
string to array[0]
and array[1]
. For copying C-strings, you normally use strcpy
.
char temp[] = "hello";
strcpy(array[0], temp);
strcpy(array[1], temp);
However, before copying you need to make sure array[0]
and array[1]
point to memory that has enough space to hold all characters of "hello"
, including the terminating null character. So you have to do something like this before calling strcpy
:
array[0] = malloc(6);
array[1] = malloc(6);
(6 is the minimum numbers of characters that can hold "hello"
.)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments