Create a function in C that takes a string as a parameter and copy it to a new string. If the original string is "abc", then the new string should be "aabbcc", if the original string is "4", then the newstring should be 44 etc. I believe i understand the concepts needed to solve a problem like this, but i just can't get the new string to be printed in the console. Here is my function:
void eco(char * str)
{
int count = 0;
/*Counts the number of symbols in the string*/
while(*(str + count) != '\0')
{
count++;
}
/*Memory for the new string, wich should be 6 chars long ("aabbcc").*/
char * newstr = malloc(sizeof(char *) * (count * 2));
/*Creating the content for newstr.*/
while(count > 0)
{
*newstr = *str; //newstr[0] = 'a'
*newstr++; //next newstr pos
*newstr = *str; //newstr[1] = 'a'
*str++; //next strpos
count--;
}
/*I can't understand why this would not print aabbcc*/
printf("%s", newstr);
/*free newstr from memory*/
free(newstr);
}
I have tried to print every char individually inside the while loop that creates the content for newstr, and that work. But when i try with the "%s"-flag i either get strange non-keyboard symbols or nothing at all.
malloc(sizeof(char *)is almost certainly not what you want.newstr, so that it's no longer pointing to the beginning of the string when you want to display it.