简体   繁体   English

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

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

I'm having problems with array of struct. 我在结构数组方面遇到问题。 I'm trying to copy a part of a string to an element of an array of struct. 我正在尝试将字符串的一部分复制到struct数组的元素中。 (sorry if it does not sound so clear) (对不起,如果听起来不太清楚)

here is my code 这是我的代码

#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;
}

It compiles but it does segmentation fault and I don't know what's wrong with it please help 它可以编译,但确实存在分段错误,我不知道它有什么问题,请帮忙

while(a != 't' ) this is infinite loop while(a != 't' )这是无限循环

did you mean 你的意思是

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

?

ADD

for this task for is more clear 此任务for更清晰

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

One possibility of segmentation fault in your code is stack overflow. 代码中的分段错误的一种可能是堆栈溢出。

Each variable of your structure will be of about 17KB size and you are creating 2562 such variables which means a total of about 43554KB needs to be allocated which 42MB. 您的结构中每个变量的大小约为17KB,您正在创建2562个此类变量,这意味着总共需要分配约43554KB的内存,其中42MB需要分配。

You can check the limit of your max stack size by doing ulimit -s from the shell, if it is less than 43554 you hit stackoverflow. 您可以通过在外壳程序中执行ulimit -s来检查最大堆栈大小的限制,如果小于43554,则可达到stackoverflow。

If this is the case you might try increasing the stack limit by doing ulimit -s 43554 or a bit more. 如果是这种情况,您可以尝试通过执行ulimit -s 43554或更多方法来增加堆栈限制。

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

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