H
HSeganfredo
Folks,
I want to write a init string function that mallocs an area, fills it
with a char, sticks a NUL char in the last position and returns it to
the user.
So far I noticed that my implementation always works over a NEW memory
area, and not over the ORIGINAL pointer area, so the initial string
area is untouched, the pointer is not update to refer to the new
initiated area...
What is going on? See my code below...
int main(){
char *string;
initstring(string, '\0', 14); /* create a string filled with NUL
and a extra NUL at position 15 */
/* if I check *string here, it is untouched since the 1st statement
*/
}
void initstring(char *array, char c, unsigned int size){
array = malloc((size + 1)* sizeof(char));
int i;
for(i=0;i<size;i++){
/* array = c; array indexing */
*array = c;
array++;
}
/* array[size+1] = '\0'; array indexing */
*array = '\0';
}
So, why "*array" always get into the function initstring with a
diferent value (memory address) than when the initistring() function
is called (according)?
My environment: Eclipse + CDT + Cygwin (Win32)
I want to write a init string function that mallocs an area, fills it
with a char, sticks a NUL char in the last position and returns it to
the user.
So far I noticed that my implementation always works over a NEW memory
area, and not over the ORIGINAL pointer area, so the initial string
area is untouched, the pointer is not update to refer to the new
initiated area...
What is going on? See my code below...
int main(){
char *string;
initstring(string, '\0', 14); /* create a string filled with NUL
and a extra NUL at position 15 */
/* if I check *string here, it is untouched since the 1st statement
*/
}
void initstring(char *array, char c, unsigned int size){
array = malloc((size + 1)* sizeof(char));
int i;
for(i=0;i<size;i++){
/* array = c; array indexing */
*array = c;
array++;
}
/* array[size+1] = '\0'; array indexing */
*array = '\0';
}
So, why "*array" always get into the function initstring with a
diferent value (memory address) than when the initistring() function
is called (according)?
My environment: Eclipse + CDT + Cygwin (Win32)