开发者

two dimensional char array in a structure gets overwritten while looping

开发者 https://www.devze.com 2023-04-10 14:40 出处:网络
I am having a struct defined like this: typedef struct stringd{ char *y; char *x[32]; }stringd; in the main program I am declaring a pointer to stringd as shown:

I am having a struct defined like this:

typedef struct stringd{
    char *y;
    char *x[32];
}stringd;

in the main program I am declaring a pointer to stringd as shown:

stringd *d = malloc(sizeof(*d));

in the main function I am parsing an input string and then storing it in a two dimensional char array

char *c[32];

Whenever I encounter a '|' character in my input string I copy the items of c to *x[32] in stringd structure. as shown below:

if (c[i][0]=='\174')
    for(j=0;j<=i;j++)开发者_开发问答{
        d[k].x[j]=c[j]; 
        c[j]=NULL;
    }
k++;

once the last string from the input(Delimiter is the space) is fetched I do the final copy of array c to x in stringd as shown(token is the pointer to the input string);

if(*token == '\0'||*token=='\n' 
    for(j=0;j<=i;j++){
        d[k].x[j]=c[j];
    }

the problem here is the strings stored earlier in the struct char array x gets overwritten by junk characters upon the last operation. Where am I going wrong?

any help appreciated,


Assuming the code you posted is run in that exact order, here's what I'm seeing:

You allocated only one stringd object. But then you increment k after your first loop. So in your final if-statement, you're accessing d[k] which is past what you allocated.

So if I'm reading this right, this is undefined behavior since you're writing into unallocated memory.

0

精彩评论

暂无评论...
验证码 换一张
取 消