简体   繁体   中英

Dynamically changing the array size of an element of data structure in C

I am new to C programming. Please excuse if this question is not appropriate. I have been struggling to dynamically change the size of a variable inside the structure (not the struct itself). Let's say I have a struct called dist1 like the code below. I want to pass this structure into a function and dynamically change the size of test1. Is this even possible?

#include <stdio.h>
struct distance
{
    double *test1;
    double *test2;
};


int main()
{
    struct distance dist1;
    add(&dist1); 

    return 0;
}

void add(struct distance *d3) 
{
     // I want to dynamically change the size of "test1" to let's say test1(50)
     // Is this possible?
}

This isn't possible in any meaningful way. You can always have struct distance container pointers to double instead of doubles, and then change the size of the pointed to memory, but your goal here isn't clear so I'm not sure what use that would be.

The members of struct distance are best first initialized.

struct distance dist1 = { NULL, NULL };

To change the the number of elements allocated, use realloc() . Pass to it d3->test1 and the number of bytes needed. If the value returned is not NULL , the re-allocation succeeded and code should use that. Research realloc() for more details.

#include <stdlib.h>
void add(struct distance *d3) {
  // I want to dynamically change the size of "test1" to let's say test1(50)
  size_t new_element_count = 50;
  void *tmp = realloc(d3->test1, sizeof *(d3->test1) * new_element_count);
  if (tmp == NULL && new_element_count > 0) {
    Handle_OutOfMemory();
  } else {
    d3->test1 = tmp;
  }
}

I was able to finally get this run. I really appreciate everybody's help and time. You guys are amazing!

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

struct distance
{
    double *test1;
    double *test2;
};


void add(struct distance *dist1) ;


int main()
{
    struct distance dist1;

    dist1.test1 = (double *) malloc(5*sizeof(double));
    dist1.test1[4] = 14.22;
    printf("dist1.test1[4] from main() = %f\n", dist1.test1[4]);

    add(&dist1); 

    printf("dist1.test2[3] from main() = %f\n", dist1.test2[3]);

    return 0;
}

void add(struct distance *dist1) 
{
     printf("dist1.test1[4] from add() = %f\n", (*dist1).test1[4]);

     (*dist1).test2 = (double *) malloc(10*sizeof(double));
     (*dist1).test2[3] = 14.67;
     printf("dist1.test2[3] from add() = %f\n", (*dist1).test2[3]);
}

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