Hi Guys,
Greetings you in the forum! I would like to use char array manipulations instead of using strcpy/strcat methods.
So I created a C function which require a char array as an input parameter and it returns with the new char array ( which contains the input parameter 3 times succesively )
After running the program I got some bizarre, strange characters on the console: The result: dogsdogsdogsh=C:zńĹKÄ☺
It is a bit disturbing for me... What do you think, which would be my problem? What is the background of the correct memory allocation ?
Any help would be appreciated! Very thx for your help!
Here is my code snippet, you can run it ( I use DevCpp ):
Code:
#include<stdio.h>
char *WriteParamStr3Times(char* paramStr); // the prototype of the function
main()
{
// define maximum 10 long string
char myString[10]="dogs";
// call the function which writes the parameter 3 times successively
char *resultString = WriteParamStr3Times(myString);
// write result string
printf("The result: %s", resultString);
}
// try to write 3times in consecutive mode
char *WriteParamStr3Times(char* paramStr)
{
char *lokalStr = (char *) malloc(strlen(paramStr)*3); // allocate memory 3x the parameter string
int i, j;
for (i=0, j=0; i< strlen(paramStr)*3; i++, j++)
{
if( j == strlen(paramStr)) // when paramStr finished, starting again
{
j=0;
}
lokalStr[i] = paramStr[j];
}
return lokalStr;
}