如何在c中将char数组设置为字符串 [英] how to set char array to string in c

查看:84
本文介绍了如何在c中将char数组设置为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个结构调用Process_Info

so i have a struct call Process_Info

  struct Process_Info {
    char name[128];
    int pid;
    int parent_pid;
    int priority;
    int status;
      };

和一组Process_Info调用信息.我将info中的pid设置为整数,但是可以正常工作,但是当我尝试将info中的名称设置为"{kernel}"时

and an array of Process_Info call info. I set pid in info to an integer, it works but when I try to set name in info to "{kernel}" like this

info[i].name="{kernel}";

,它在赋值错误中给了我不兼容的类型.我在网上搜索,似乎可以做到,例如 http: //www.cs.bu.edu/teaching/cpp/string/array-vs-ptr/,他们做了char label [] ="Single";那我在做什么错了?

and it give me incompatible type in assignment error. I search online it seem i can do this, like in http://www.cs.bu.edu/teaching/cpp/string/array-vs-ptr/, they did char label[] = "Single"; So what am i doing wrong?

推荐答案

简而言之:AC编译器会将常量字符串烘焙到二进制文件中,因此您需要使用strncpy (或 strcpy (如果您不担心安全性)将"{kernel}"复制到info[i].name.

The short answer: A C compiler will bake constant strings into the binary, so you need to use strncpy (or strcpy if you aren't worried about security) to copy "{kernel}" into info[i].name.

更长的答案:每当你写

char label[] = "Single";

C编译器会将字符串"Single"烘烤到它生成的二进制文件中,并将label变成指向该字符串的指针.用C语言术语,单一"的类型为const char *,因此不能以任何方式进行更改.但是,不能将const char *分配给char *,因为可以修改char * .

the C compiler will bake the string "Single" into the binary it produces, and make label into a pointer to that string. In C language terms, "Single" is of type const char * and thus cannot be changed in any way. However, you cannot assign a const char * to a char *, since a char * can be modified.

换句话说,你不能写

char label[] = "Single";
label[0] = "T";

因为编译器不允许第二行.但是,您可以 通过编写类似

because the compiler won't allow the second line. However, you can change info[i].name by writing something like

info[i].name[0] = '[';

因为info[i].name如果是char *类型.要解决此问题,您应该使用strncpy(我在上面参考了手册页)将字符串"{{Kernel}""复制为info[i].name as

because info[i].name if of type char *. To solve this problem, you should use strncpy (I referenced a manual page above) to copy the string "{Kernel}" into info[i].name as

strncpy(info[i].name, "{Kernel}", 256);
info[i].name[255] = '\0';

这将确保您不会溢出缓冲区.

which will ensure that you don't overflow the buffer.

这篇关于如何在c中将char数组设置为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆