Inquiries about structure pointer arrangement

Asked 2 years ago, Updated 2 years ago, 78 views

Hello.

strcpy(lp[1]->Korea, "o"); What is the cause of the error in this part?

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

typedef struct{
    char korea[20];
} } test;

int main()
{
    test *lp[3];

    for(int i=0; i<sizeof(lp)/sizeof(test); i++)
    {
        lp[i] = malloc(sizeof(test));
    }

    strcpy(lp[0]->korea, "k");
    strcpy(lp[1]->korea, "o");
    printf("%s", *lp);
    return 0;
}

struct

2022-09-22 21:56

2 Answers

I don't know the intention of the other parts of the code.

For statement

for(int i=0; i<sizeof(lp)/sizeof(test); i++)
{
    lp[i] = malloc(sizeof(test));
}

The intention seems to repeat three times, but it actually only runs once.

Why is the denominator sizeof(test) 20

Because the numerator sizeof(lp) is 8 * 3 = 24.

lp is a variable that has an array of pointers to the test structure. Therefore, there are not three 20bytes, but three 8bytes, the size of the pointer.

Eventually, the size check result, which is the end condition of the for statement, is always casted with (int)1 The segmentation fault 11 error occurs as soon as you attempt to access the lp[1] memory below. It's because it's dynamically allocated, so there's an error.

If you want to write in a direction where there are no errors,

//for(int i=0; i<sizeof(lp)/sizeof(*lp); i++)
//{
//    //    lp[i] = malloc(sizeof(test));
//}
//
// Oh, I'm modifying the code. I think the bottom is correct
for(int i=0; i<sizeof(lp)/sizeof(test *); i++)
{
    lp[i] = malloc(sizeof(test));
}

Wouldn't it be like this?


2022-09-22 21:56

lp[i] = malloc(sizeof(test));

Does not cause compilation errors?

lp[i] = (test*)malloc(sizeof(test));

You have to change the shape like this.


2022-09-22 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.