开发者

how to store a string using array in c?

开发者 https://www.devze.com 2023-01-23 00:55 出处:网络
in php $arr = array() $arr[0] = \"string 1\"; $arr[1] = \"开发者_C百科string 2\"; how about in c? thanksYou need to declare an array of pointers. Each element of the array is a pointer to the str

in php

$arr = array()
$arr[0] = "string 1";
$arr[1] = "开发者_C百科string 2";

how about in c?

thanks


You need to declare an array of pointers. Each element of the array is a pointer to the string. You need to copy the string in, and then release it when done.

char *strings[2];

strings[0] = strdup("Hello, world!");
printf("%s\n", strings[0]);
free(strings[0]);


There are several ways to do that:

  • This will allocate enough space in the data segment of the program to store the string, and store the address of the string, in the "arr" variable, which can then be accessed just like an array.
char *arr = "First String";
char a = arr[2];
  • Another way is to allocate memory for the string and then store it in that memory which can subsequently be accessed like an array:
char a;
char *str = (void *) malloc(14);
strncpy(str, "Second String", 14);
a = str[2];
  • Third way is to just declare an array of a certain size and assign a string to it:
char str[14] = "Third String";

Here is a good discussion of Arrays and Pointers in C.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号