Tag: strncpy

使用strcpy时打印垃圾

我有一个函数可以解析一些数据。我的问题是在使用strncpy后,当我尝试打印它时会得到一些垃圾。 我尝试使用malloc使char数组具有确切的大小。 码: void parse_data(char *unparsed_data) { char *temp_str; char *pos; char *pos2; char *key; char *data; const char newline = ‘\n’; int timestamp = 0; temp_str = (char*)malloc(strlen(unparsed_data)); g_print(“\nThe original string is: \n%s\n”,unparsed_data); //Ignore the first two lines pos = strchr(unparsed_data, newline); strcpy(temp_str, pos+1); pos = strchr(temp_str, newline); strcpy(temp_str, pos+1); //Split the line in […]

在我的情况下strncpy或strlcpy

当我想将src_str复制到dst_arr时,我应该使用什么?为什么? char dst_arr[10]; char *src_str = “hello”; PS:在阅读了很多关于strncpy和strlcpy 好坏的事情之后,我的头比我的电脑磁盘旋转得更快。 注意:我知道strlcpy无处不在。 这不是问题所在。

strncpy导致分段错误

我只是乱搞strncpy。 我的程序看起来像这样 typedef struct { char from_str[10]; }test; main () { test s1; memset(&s1,0,sizeof(test)); char src[10]=”himansh”; char dest[10]; memset(dest,0,10); src[3]=’\0′; printf(“src is %s and strlen is %d \n”, src,strlen(src)); fflush(stdout); strncpy(s1.from_str,src,100); printf(“s1.from_str is %s , src is %s \n”, s1.from_str,src); return 1; } 在我执行strncpy之前,我在“src”字符串中添加了一个“\ 0”字符,“src”字符串的长度变为3,目标数组的大小为10。但是在strncpy中我将要复制的字节数复制为100 。 这意味着我的源字符串以NULL结尾。 现在strncpy像任何字符串函数一样,即使我提供的字节数大于3(在本例中为100),也应该尝试仅复制3个字节。 它做到了,但我也得到了分段错误。 我的结果如下所示 src is him and strlen […]

strncpy和memcpy之间的区别?

我如何在s访问s[7] ? 我没有发现strncpy和memcpy之间有任何区别。 如果我想打印输出s ,连同s[7] (如qwertyA ),我必须在以下代码中做出哪些更改: #include #include int main() { char s[10] = “qwerty”, str[10], str1[10]; s[7] = ‘A’; printf(“%s\n”,s); strncpy(str,s,8); printf(“%s\n”,str); memcpy(str1,s,8); printf(“%s\n”,str1); return 0; } /* O/P qwerty qwerty qwerty */