0

I'm trying to copy a even number of char in another string. It does not work at all. But if I try to copy a odd number of char it works. I try to use a for and the function strncpy and it print the word that I want plus a randome letter.

int position=6;
char *stringFirst=malloc(position);

for(int j=0;j<position;j++){
    stringFirst[j]=fileStingToMod[j];
}

printf("%s",stringFirst);
free(stringFirst);

This is another code that I try to run:

int position=6;
char *stringFirst=malloc(position);

strncpy(stringFirst,fileStingToMod,position);

printf("%s",stringFirst);
free(stringFirst);

In both cases, the code gives me the following output:

cammelÙ

or

cammel↓

The string, named fileStringToMod, is : "cammelloverde".

  • 3
    If you want to apply string-format operations on that array of characters, then you set the last character to 0 (null character). – goodvibration Aug 31 '20 at 14:29
  • 1
    `printf("%s",stringFirst)` is an example of a string-format operation. – goodvibration Aug 31 '20 at 14:30
  • Thanks a lot man, I'm really dumb. But I have a question: Why my code worked with odd nomber of character and not with even number of character? –  Aug 31 '20 at 14:37
  • 1
    @LudovicoLatini undefined behavior does not need to provide wrong results. That's the bad thing about it. It has nothing to do with the number being odd. – RobertS supports Monica Cellio Aug 31 '20 at 14:38

2 Answers2

3

Only the first six characters of fileStringtoMod are copied to the memory pointed by stringFirst.

Note that a null terminator is missing to determine the end of a string.

The %s format specifier is to print strings, which need to be determined by null, but stringFirst has no null terminator.

Using printf("%s",stringFirst); invokes undefined behavior.

Use

stringFirst[position-1] = '\0';

before

printf("%s",stringFirst);

if you only want to print "camme".


Alternatively, you could use

printf("%.*s", position, stringFirst);

as suggested by @IngoLeonhardt the comments or

printf("%.6s", stringFirst);

even without having a null terminator in the string.


If you want to print 6 characters (like "cammel") you need to allocate memory for 7, not 6 characters as you always need a null terminator to representing strings.

0

You didn't specify the contents of FileStingToMod, but I just guess it is a longer string.

The problem is that in C strings are terminated by a '\0' character, which you are not adding to your new string.

int position = 6;
char *stringFirst = malloc(position);
for(int j=0; j<position-1; j++) {
    stringFirst[j]=fileStingToMod[j];
}
stringFirst[position-1] = '\0';
printf("%s",stringFirst);
free(stringFirst);