简体   繁体   English

如何在C中的多维数组中存储字符串?

[英]How do I store a string in an multidimensional array in C?

I feel silly for asking, but I had trouble finding my answer. 我发问很傻,但是我很难找到答案。 How do I re-assign "Rose" to "Douglas"? 如何将“罗斯”重新分配给“道格拉斯”? It seems like I have to use a loop. 看来我必须使用循环。

#include <stdio.h>

int main() {

  char arr[3][12]= { "Rose", "India", "technologies" };
  printf("Array of String is = %s,%s,%s\n", arr[0], arr[1], arr[2]);
  arr[0][0] = {"Douglas"};
  printf("Array of String is = %s,%s,%s\n", arr[0], arr[1], arr[2]);

    return(0);
}

You can do this with strcpy() : 您可以使用strcpy()做到这一点:

strcpy(arr[0], "Douglas");

When using strcpy() , you will have to ensure that there is enough space in the destination to hold the string you're putting there (plus the terminating NUL character). 使用strcpy() ,必须确保目标中有足够的空间来容纳要放在其中的字符串(加上终止符NUL字符)。 In this case there is, because you have allocated 12 bytes for each string and "Douglas" will take 8. 在这种情况下,因为为每个字符串分配了12个字节, "Douglas"将占用8个字节。

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

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