简体   繁体   中英

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. (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

did you mean

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

?

ADD

for this task for is more clear

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.

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.

If this is the case you might try increasing the stack limit by doing ulimit -s 43554 or a bit more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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