Hi,
I am trying copy a string over another string and I wrote the following code:
Code:
/* Params: toAssign: The string to overwrite.
value: The new value of the string should have
valuelengt: The length of the value*/
int assignValue(char *toAssign, char *value, int valuelength)
{
if ((toAssign = malloc(valuelength*sizeof(char)))==NULL) return (0);
int i;
for (i=0;i<valuelength;i++)
toAssign[i]=value[i];
toAssign[valuelength] = '\0';
//printf("toassogn: %s",toAssign);
return(1);
}
int main()
{
char string[] = "test1";
char string2[] = "blablabla";
/*Trying to copy string2 over string */
if (!assignValue(string, string2, sizeof string2)){
printf("Something went wrong...");
return (EXIT_FAILURE);
}
printf("%s\n", string);
return(EXIT_SUCCESS);
}
In this case I am trying to copy string2 ("blablabla") over string ("test1")
If I get it correctly when calling assignValue the pointers of the first elements of "string" and "string2" are passed into the function. In the function I allocate new memmory space and I make the pointer toAssign to point to that space. Then I copy the elements of the second array to the newly allocated space.
When assignValue exits and the control is returned to main "string" should point to the newly allocated memory, right? Well, it doesn't (i.e. the printf) statement in main() prints "test1"). So I guess something is wrong in the way I think about it?