#Allocating integer arrays

7 messages · Page 1 of 1 (latest)

modern citrus
#

Hi guys! This is my 2nd exercise regarding this topic. Myself and most of my classmates are completely lost. I've tried to do the function part first, does it look correct or could I get any tips on what's wrong?

All kinds of tips are extremely appreciated. I'm reading my C book like a lunatic to find something that will help me.

So the code I've been writing this far is:

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

int** expand(int n, int* v); //prototype

int main() 
{
    int n;
    int **Matrix;

    while(scanf("%d", &n)==1)
    {

    }

}

int** expand(int n, int* v)
{
    int **Matrix = malloc(sizeof(int*) * *v);
    if (Matrix)
        memcpy(Matrix, n, sizeof(int*) * *v);
    return Matrix;

}
whole trellisBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

placid fiber
#

For expand, I would do something like

int **expand(int n, int *v)
{
     int  i;
     int  j;
     int  **matrix;

     i = 0;
     j = 0;
     matrix = malloc(sizeof(int *) * n);
     while (i < n)
     {
          matrix[i] = malloc(sizeof(int) * n);
          j = 0;
          while (j < n)
          {
               matrix[i][j] = v[i];
               j++;
          }
          i++
     }
     return (matrix);
}

To print the matrix, its more or less the same thing. If you are working with a matrix, always use a nested loop

modern citrus
#

Thanks for the tip! 🙂

placid fiber
#

np ^^

whole trellisBOT
#

@modern citrus Has your question been resolved? If so, run !solved :)

modern citrus
#

!solved