Hi Salem,
Very thx for your useful remarks, then I tried to test my program using max length of the parameter string.
Code:
char myString[10]="dogs_cats"; // this means: 'd' 'o' 'g 's' '_' 'c' 'a' 't' 's' '/0'
As I imagine the size of the memory allocation needs 3 times of the length string ( 'd' 'o' 'g 's' '_' 'c' 'a' 't' 's' '/0' - the string contains the closing literal ) and additionally the closing character for the end ( '\0')
Code:
#include<stdio.h>
char *WriteParamStr3Times(char* paramStr); // the prototype of the function
main()
{
// define maximum 10 long string
char myString[10]="dogs_cats"; // 'd' 'o' 'g 's' '_' 'c' 'a' 't' 's' '/0' -> this is the max length of the characters
// 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 = malloc(strlen(paramStr)*3); // allocate memory 3x the parameter string - Currently it works without any problem
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];
}
lokalStr[i]='\0';
return lokalStr;
}
But with my ide ( DevCPP ) it works with the code (as attached above ) without increasing the allocation size of the 'lokalStr' +1. Is it necessary to allocate +1 unit for the string? But just to be on the safe side can we allocate memory for the last closing literal ('\0') ?
Very thanks for your help!