简体   繁体   中英

Understanding why I need malloc

I would like to understand why I needed to use malloc in this. The goal of my code was to separate "]" and ")" from ";". So like this "];" into "]" ";" and ");" into ")" ";" . ptr is being used as an array of strings. I can't remember the technical name of array of strings. This works perfectly, but it save me lots of time to understand why this happened in the future.

char  *ptr[buflen];
for(x = 0; x < n; x++)
{
    printf("ptr[x] is %s \n", ptr[x]);
    cmp_str3 = strcmp(ptr[x], "];");
    cmp_str4 = strcmp(ptr[x], ");");
    if(cmp_str3 == 0)
    {
        printf("Match1 \n");
        strcpy(str1, ptr[x]);
        printf("Match2 \n");
        ptr[x][1] = '\0';
        printf("Match3 \n");
        //printf("ptr[x+1] %c %d \n", ptr[x+1], ptr[x+1]);
        //printf("ptr[x+1][0] %c %d \n", ptr[x+1][0], ptr[x+1][0]);
        ptr[x+1] = malloc(strlen("foo") + 1);
        ptr[x+1][0] = str1[1];
        printf("Match4 \n");
        ptr[x+1][1] = '\0';
        printf("Match5 \n");
        n++;
    }
    if(cmp_str4 == 0)
    {
    }
}
cmp_str3 = 0;
cmp_str4 = 0;
memset(str1, 0, 15);
memset(str2, 0, 15);

The declaration

char *ptr[buflen];

creates an array of pointers. If ptr is a local variable (inside of a function) then the pointers are initially garbage values, they don't point to valid memory. If ptr is global or static, then the pointers are initially NULL .

In any case, before you can use one of the pointers to point to a string, the string needs to be in memory somewhere.

Given the line

char *ptr[3] = {"foo", "bar", "bletch"};

the compiler takes care of allocating memory for the strings, and then puts pointers to the strings into the array.

But if the strings aren't constant, then you have to allocate memory for the string yourself. That's what malloc does. It allocates the number of bytes that you request, and returns a pointer to that memory. You can save that pointer in the array, and then use strcpy or the other string functions to put the string into that memory.

Or you can copy characters one at time, which is what your code does:

ptr[x+1] = malloc(2);     // reserves two bytes of memory, and keeps the pointer 
                          // to that memory in the array of pointers
ptr[x+1][0] = str[1];     // copies a character into the first byte of the memory
ptr[x+1][1] = '\0';       // marks the second byte as the end of the string

So now you have a string in memory, and a pointer to that string in the array of pointers.

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