繁体   English   中英

如何将字符串的一部分复制到struct数组的元素?

[英]How to copy a part of a string to an element of array of struct?

我在结构数组方面遇到问题。 我正在尝试将字符串的一部分复制到struct数组的元素中。 (对不起,如果听起来不太清楚)

这是我的代码

#include <stdio.h>
#include <string.h>

struct dict {

char key[1024];

char value[16384];

int level;

};

int main()
{
struct dict entry[2562];
char str[]="i will finish my mp";
int j=0;
int i = 0;
char temp[1024];
char a =0;

while(a != 'h' ){
    a = str[i];
    temp[i] = str[i];
    i++;
} 
strcpy(entry[0].value,str);
puts(entry[0].value);



return 0;
}

它可以编译,但确实存在分段错误,我不知道它有什么问题,请帮忙

while(a != 't' )这是无限循环

你的意思是

char a = 0xff;
while(a != '\0'){...} 

此任务for更清晰

int cnt = srtlen(str);
for(int i = 0; i < cnt; i++)
    temp[i] = str[i];

代码中的分段错误的一种可能是堆栈溢出。

您的结构中每个变量的大小约为17KB,您正在创建2562个此类变量,这意味着总共需要分配约43554KB的内存,其中42MB需要分配。

您可以通过在外壳程序中执行ulimit -s来检查最大堆栈大小的限制,如果小于43554,则可达到stackoverflow。

如果是这种情况,您可以尝试通过执行ulimit -s 43554或更多方法来增加堆栈限制。

暂无
暂无

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

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