在C字符串赋值 [英] String assignment in C

查看:121
本文介绍了在C字符串赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来C.在以下code中的字符串赋值如下:

I'm new to C. The string assignment in the following code works:

#include<stdio.h>
int main(void){
  char str[] = "string";
  printf("%s\n",str);
}

但不会在下面的工作,即使我给索引号为名称[]

#include <stdio.h>
int main(void){
  struct student {
    char name[10];
    int  salary;
  };
  struct student a;
  a.name[10] = "Markson";
  a.salary = 100;
  printf("the name is %s\n",a.name);
  return 0;
}

为什么会出现这种情况?

Why does this happen?

推荐答案

您不能分配到一个数组。两个解决方案:要么复制字符串:

You can't assign to an array. Two solutions: either copy the string:

strcpy(a.name, "Markson");

或使用一个const char指针,而不是一个数组,然后你可以简单地给它分配:

or use a const char pointer instead of an array and then you can simply assign it:

struct {
    const char *name;
    /* etc. */
};

a.name = "Markson";

或者使用非const字符指针,如果你想修改名之后的内容:

Or use a non-const char pointer if you wish to modify the contents of "name" later:

struct {
    char *name;
}

a.name = strdup("Markson");

(不要忘了以释放的strdup()在后一种情况下分配的内存!)

(Don't forget to free the memory allocated by strdup() in this latter case!)

这篇关于在C字符串赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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