简体   繁体   中英

dynamically allocating an array of dynamically allocated strings in c

I'm new to C and I'm having a problem with saving dynamically allocated strings in dynamically allocated array. I tried to look at a simple example:

int*    p_array;

// call malloc to allocate that appropriate number of bytes for the array

p_array = malloc(sizeof(int) * 3);      // allocate 3 ints


// use [] notation to access array buckets
for (int i = 0; i < 3; i++) {
    p_array[i] = 1;
}

however, when I'm debugging it in visual studio it seems like I don't have an array with 3 slots, in p_array it shows me only {1} . the same problem happened to me with my actual code that I'm trying to write: in the actual code, I get from the user a polynomial in the running time, and need to put in an array each term of the polynomial in a different cell. I don't know the polynomial length so I need to allocate the array dynamically. in this example I wrote a constant string as the polynomial for your help. the I'm trying to enter to the array the terms but as the other example, in the debugging I only see at the end the array {2x}

char[] polynom = "2x +5x^2 +8";
char* term;
char** polyTerms;
int i=0;
term = strtok(polynom, " ");
polyTerms = (char**)malloc(3* sizeof(polynom));


while (term != NULL)
{

    polyTerms[i] = (char *)calloc(strlen(term) + 1, sizeof(char));
    strcpy(polyTerms[i], term);
    term = strtok(NULL, " ");

    i += 1;
}

I appreciate any help!

First code snippet:

The debugger doesn't know how much you have allocated in p_array and therefore it doesn't display the size of the array and more than the first element. BTW p_array is not an array but just a pointer to int .

Second code snippet:

The code looks correct to me but it's:

char polynom[] = "2x +5x^2 +8";    

and not

char[] polynom = "2x +5x^2 +8";

When allocating the array of pointers you need to make sure you are allocating enough space.

(char**)malloc(3* sizeof(polynom));

Will most likely not allocate all the memory needed.

Use:

polyTerms = malloc(sizeof term * sizeof polynom);

Also, you may want to look into using strdup() in your code that allocates and copies into your array.

polyTerms[i] = (char *)calloc(strlen(term) + 1, sizeof(char));
strcpy(polyTerms[i], term);

Can become:

polyTerms[i] = _strdup(term); // VS2013 version of POSIX strdup()

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