简体   繁体   English

c - 如何将偶数个字符复制到C中的字符串?

[英]How to copy an even number of char to a string in C?

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.我尝试使用 for 和函数 strncpy 并打印我想要的单词和随机字母。

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" .名为fileStringToMod的字符串是: "cammelloverde"

Only the first six characters of fileStringtoMod are copied to the memory pointed by stringFirst .只有fileStringtoMod的前六个字符被复制到stringFirst指向的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. %s格式说明符是打印字符串,需要由 null 确定,但stringFirst没有 null 终止符。

Using printf("%s",stringFirst);使用printf("%s",stringFirst); invokes undefined behavior .调用未定义的行为

Use

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

before

printf("%s",stringFirst);

if you only want to print "camme" .如果您只想打印"camme"


Alternatively, you could use或者,您可以使用

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

as suggested by @IngoLeonhardt the comments or正如@IngoLeonhardt 所建议的,评论或

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.如果您想打印 6 个字符(如“cammel”),您需要为 7 个而不是 6 个字符分配内存,因为您总是需要一个空终止符来表示字符串。

You didn't specify the contents of FileStingToMod, but I just guess it is a longer string.您没有指定 FileStingToMod 的内容,但我猜它是一个较长的字符串。

The problem is that in C strings are terminated by a '\\0' character, which you are not adding to your new string.问题是在 C 中字符串以 '\\0' 字符终止,您没有将其添加到新字符串中。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM