Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Duplicar una matriz dinámicamente

Estoy tratando de resolver el siguiente ejercicio en C:

"Considere una función dobuleArray () que toma como entrada una matriz y un puntero a su tamaño y da como salida la matriz duplicada. Cree una matriz de tamaño 1 a 4 como tamaño inicial. Luego, comience a llenar la matriz con 2048 enteros generados aleatoriamente ; cada vez que el arreglo esté lleno, llame a la función doubleArray() ​. Después de cada invocación de ​ doubleArray()​ , imprima nuevamente el contenido del arreglo"​

Tengo problemas con un tamaño inicial de 3. El programa que he escrito no funciona para números mayores de 4 y tampoco sé por qué. Precisamente, obtengo un realloc: invalid next size

 int* doubleArray(int* vect, int* dim) { int old_dim = *dim; int i; int new_dim = old_dim * 2; vect = realloc(vect, new_dim * sizeof(int)); for (i = old_dim; i < new_dim; i++) { vect[i] = 0; } *dim = new_dim; return vect; } int main() { int n = 3; int* size = &n; int* arr = malloc(n * sizeof(int)); for (int i = 0; i < 2048; i++) { if (i > *size) { int j = 0; // used to count the size of the doubled-array each time the // if condition is true arr = doubleArray(arr, size); for (int i = 0; i < *size; i++) { j++; printf("%d ", arr[i]); } printf("\n"); printf("%d\n", j); printf("\n"); arr[i] = rand() % 6; } else { arr[i] = rand() % 6; } } }

La doble función debería funcionar correctamente, creo. El programa completo realmente funciona solo para valores tales como 2048 % value == 0 . Pero supongo que debería haber una manera de corregirlo para que funcione para 3.

Explícitamente, la salida de este programa se ve así:

 1 4 3 0 0 0 6 realloc(): invalid next size signal: aborted (core dumped)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Escribe más allá del final de la matriz, lo que provoca un comportamiento indefinido. (comportamiento indefinido bastante molesto en este caso)

 if (i > *size) {

debiera ser

 if (i >= *size) {
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!