[英]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++;
}
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. printf语句工作正常,这表明它不是导致问题的节点字段,但是当我执行我的sprintf语句将字符串复制到数组的索引中时。 I get a segmentation fault.
我遇到了分段错误。
You only declare 你只申报
char *list[numNodes];
but not allocate memory for them. 但不为他们分配内存。 Before using
list[i]
allocate memory with malloc
. 在使用
list[i]
之前使用malloc
分配内存。 To know the size of generated string from sprintf
use snprintf
. 要知道
sprintf
生成的字符串的大小,请使用snprintf
。 Thanks user3121023 for finding us this function. 感谢user3121023找到我们这个功能。
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++;
}
You are not initializing the array of char pointers-- sprintf is writing data to some random location. 您没有初始化char指针数组 - sprintf正在将数据写入某个随机位置。
Each char pointer should be initialized to a buffer with malloc before you call sprintf. 在调用sprintf之前,应将每个char指针初始化为具有malloc的缓冲区。
list is defined but each element has no/random pointer in it. 列表已定义,但每个元素中都没有/随机指针。 The above answers are complete but this can be simplified a bit:
上面的答案已经完成,但这可以简化一下:
void listToArray(){
//create array of strings
char *list[numNodes];
char buf[5000];
int i = 0, n;
while (head != NULL) {
snprintf(buf,sizeof(buf),"[%d] %s %s:%d\n ",
i,head->fileName,head->ip,head->port);
// add string to array
list[i] = strdup(buf);
// output
fputs(list[i],stdout);
head = head->next;
i++;
}
}
You only need to do a single printf/sprintf. 你只需要做一个printf / sprintf。 That's the slow part.
那是缓慢的部分。 Doing a single snprintf and strdup is faster and simpler than doing 2-3 *printf calls.
执行单个snprintf和strdup比执行2-3 * printf调用更快更简单。 I'm guessing that you only want one output line per item and the rest were for debug.
我猜你每个项目只需要一个输出行,其余的用于调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.