不能字符串复制到字符串C中的数组 [英] Can't copy string to an array of strings in C
问题描述
我想通过我的链接列表遍历每个节点的字段合并为一个字符串,然后添加字符串转换成字符串数组。
I'm trying to traverse through my linked list and combine each of the nodes fields into a string, and then add the string into an array of strings.
void listToArray(){
//create array of strings
char *list[numNodes];
int i = 0, n;
while(head != NULL){
// add string to array
printf("[%d] %s %s:%d\n ", i, head->fileName, head->ip, head->port);
n = sprintf(list[i], "[%d] %s %s:%d\n", i, head->fileName, head->ip, head->port);
head = head->next;
printf("%s\n", list[i]);
i++;
}
printf语句工作正常,这表明它不是节点,它是导致问题的领域,但是当我做我的sprintf语句将字符串复制到数组的索引。我得到一个分段错误。
The printf statement works fine, which shows that it is not the fields of node that are causing the problem, but when I do my sprintf statement to copy the string into the index of the array. I get a segmentation fault.
推荐答案
您只声明
char *list[numNodes];
但他们不分配内存。使用列表[I]之前
与的malloc
分配内存。要知道生成的字符串,从的sprintf
尺寸使用的snprintf
。由于 user3121023 寻找我们这个功能。
but not allocate memory for them. Before using list[i]
allocate memory with malloc
. To know the size of generated string from sprintf
use snprintf
. Thanks user3121023 for finding us this function.
void listToArray(){
//create array of strings
char *list[numNodes];
int i = 0, n;
while(head != NULL){
printf("[%d] %s %s:%d\n ", i, head->fileName, head->ip, head->port);
n = snprintf(NULL, 0, "[%d] %s %s:%d\n", i, head->fileName, head->ip, head->port);
list[i] = malloc((n+1)*sizeof(char));
n = sprintf(list[i], "[%d] %s %s:%d\n", i, head->fileName, head->ip, head->port);
head = head->next;
printf("%s\n", list[i]);
i++;
}
这篇关于不能字符串复制到字符串C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!