Vector of Vectors on C - c

I'm new here and this is my first question, i couldn't find anything like this in the search engine so my problem is basically a vector of vectors on C, here is what i have done until now but i keep getting a deadly warning, so i know that I'm not using well the structure with the vector and I'd really appreciate some help.
Thanks
PD: Sorry for my english.
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int n;
int *vector;
}Vector_T;
int inicializar_original(int *n,int dim)
{
int i,r,s,j,*k;
Vector_T *t;
Vector_T l;
srand(time(NULL));
r=rand()%10;
scanf("%d",&s);
t->vector=k;
l.n=s;
k=(int*)malloc(s*sizeof(int));
for(j=0;j<s;j++)
{
k[j]=r;
}
for(i=0;i<dim;i++)
{
n[i]=k;
}
}
int main()
{
int *v,dim;
scanf("%d",&dim);
v=(int*)malloc(dim*sizeof(int));
inicializar_original(v,dim);
}

Asumo que hablas español, así que aquí va: El problema más grande es que no estás inicializando la variable "k". Mi sugerencia es que intentes lo siguente:
int i,r,s,j;
int* k;
If English only: Your problem is probably that you're initializing K in the wrong way. Try to do:
int i,r,s,j;
int* k;

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int n;
int *vector;
}Vector_T;
int inicializar_original(Vector_T *v, int dim){
int i, j, s, r = rand()%10;
scanf("%d", &s);
for(i=0; i<dim; i++){
int *k = malloc( s * sizeof(int));
for(j=0; j<s; j++){
k[j]=r;
}
v[i].n = s;
v[i].vector = k;
}
}
int main(void){
Vector_T *v;
int dim;
srand(time(NULL));
scanf("%d", &dim);
v = malloc(dim * sizeof(*v));
inicializar_original(v, dim);
{ //check print & release
int i, j;
for(i = 0; i < dim; ++i){
for(j = 0; j < v[i].n ; ++j){
printf("%d ", v[i].vector[j]);
}
puts("");
free(v[i].vector);
}
free(v);
}
return 0;
}

Related

Copy of random matrix in C

Just as the title says, here I ask for two inputs in order to generate a matrix based on such inputs from the user, which then will be filled with random numbers up to the number 20.The problem is I can't wrap my head around the logic needed to generate an exact copy of this matrix without generating a second matrix with randomly generated numbers(again) so I can make useof the data stored in the copy.
(Edit)
I've added an image as reference of what I'm trying to achieve.
I tried to store the random values in a one dimensional array, so I can use them later, but I'm not sure if it is the right approach. I'm relatively new to coding and still struggling with the basics, so any help will be greatly appreciated.
Here´s the code that generates the matrix and stores random int values in it.
#include <stdio.h>
#include<time.h>
int matrizAleatoria(int m, int n, int r);
int srand();
int rand();
int main()
{
int m, n;
printf("Introduce el numero de filas:\n");
scanf("%d", &m);
printf("Introduce el numero de columnas:\n");
scanf("%d", &n);
printf("\n");
srand(time(0));
int r = (rand()% 20);
matrizAleatoria(m, n, r);
printf("\n");
return 0;
}
int matrizAleatoria(int m, int n, int r)
{
int i, j, p = m * n;
int matriz1[m][n];
int serie[p];
for(i = 0; i<m; i++)
{
for(j = 0; j<n; j++)
{
matriz1[i][j] = r = (rand()% 20);
serie[i] = r;
printf("[ %-2d ] " , matriz1[i][j]);
}
printf("\n");
}
return serie[i];
}
You cannot return a variable-sized array from a function to outside scope. You have to implement 2-dimensional subscripts yourself and only work with pointers. Like this:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define SUBSCRIPT_2DIM_TO_1DIM(subscript1, subscript2, size2) \
((subscript1) * (size2) + (subscript2))
int* matrizAleatoria(int m, int n);
int main()
{
int m, n;
int* matriz1;
printf("Introduce el numero de filas:\n");
scanf("%d", &m);
printf("Introduce el numero de columnas:\n");
scanf("%d", &n);
printf("\n");
srand(time(0));
matriz1 = matrizAleatoria(m, n);
printf("\n");
// use matriz1 with SUBSCRIPT_2DIM_TO_1DIM
free(matriz1);
return 0;
}
int* matrizAleatoria(int m, int n)
{
int i, j, p = m * n;
// return matrix value, must free() in the caller
int *matriz1 = malloc(sizeof(int) * p);
for(i = 0; i<m; i++)
{
for(j = 0; j<n; j++)
{
matriz1[SUBSCRIPT_2DIM_TO_1DIM(i, j, n)] = rand()% 20;
printf("[ %-2d ] " , matriz1[SUBSCRIPT_2DIM_TO_1DIM(i, j, n)]);
}
printf("\n");
}
return(matriz1);
}

c program run on codeblocks but not on clion how is it even possible?

i successfully run it on codeblocks, but my clion doesnt display anything when i run it.
i usually use clion, so im very furious about this. (dont want to be obligated to use codeblocks)
please help a poor lost soul.
this is the code.
dont have a lot more to say, but still stackoverflow wants me to write more, so here i am.
#include <stdio.h>
#include <stdlib.h>
int **malloc2dR(int r,int c);
int **MATinit(int r, int c);
void MATstampa(int **m, int r, int c);
void change(int **M, int r, int c);
int main() {
int r=3,c=4;
int **M=MATinit(r,c);
MATstampa(M,r,c);
change(M,r,c);
MATstampa(M,r,c);
return 0;
}
int **malloc2dR(int r, int c){
int **m;
int i;
m=malloc(r*sizeof (int *));
for(i=0;i<r;i++)
m[i]=malloc(c*sizeof (int));
return m;
}
int **MATinit(int r, int c){
int **M=malloc2dR(r,c);
int i,j;
printf("scrivere in input i valori della matrice %dx%d\n",r,c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&M[i][j]);
return M;
}
void MATstampa(int **m, int r, int c){
int i,j;
for(i=0;i<r;i++) {
for (j = 0; j < c; j++)
printf("%d ", m[i][j]);
printf("\n");
}
printf("\n");
}
void change(int **M, int r, int c) {
int i, j;
int ii, jj;
int **Mfake=malloc2dR(r,c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
Mfake[i][j]=M[i][j];
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
if (M[i][j] % 2 == 1) {
for (ii = 0; ii < r; ii++)
Mfake[ii][j] = 1;
for (jj = 0; jj < c; jj++)
Mfake[i][jj] = 1;
}
for(i=0;i<r;i++)
for(j=0;j<c;j++)
M[i][j]=Mfake[i][j];
}

Exception thrown at 0x00007FF93F57B016 (ucrtbased.dll) in Ficha 5.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF

I wrote some code and it showed me this error: Exception thrown at 0x00007FF93F57B016 (ucrtbased.dll) in Ficha 5.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
I can't find the reason behind it.
#include <stdio.h>
#define num 10
void ler_matriz(int **matriz1, int n, int m);
void mostrar_matriz(int matriz1[num][num], int n, int m);
//int num_min_matriz(int matriz1[][], int n, int m);
//void teste_simetria(int matriz1[][], int n, int m);
//void transposta_matriz(int matriz1[][], int n, int m);
//void soma_matriz(int matriz1[][], int matriz2[][], int matriz3[][], int n, int m);
int main()
{
int x[num][num], y[num][num], z[num][num], numL, numC;
printf("Introduza o número de linhas e colunas para a matriz:\n");
scanf(" %d%d", &numL, &numC);
printf("\n\nIntroduza os valores para a matriz 1: ");
ler_matriz(x, numL, numC);
mostrar_matriz(x, numL, numC);
return 0;
}
void ler_matriz(int **matriz1, int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("\nx[%d][%d]: ", i + 1, j + 1);
scanf(" %d", &matriz1[i][j]); // the exception error
}
}
}
void mostrar_matriz(int matriz1[num][num], int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; i < m; j++)
{
printf("%d ", matriz1[i][j]);
}
putchar('\n');
}
}
You have:
for (int j = 0; i < m; j++)
This should be
for (int j = 0; j < m; j++)
Otherwise, i < m is going to be true forever (because you're not changing i in that loop) and you'll eventually be accessing 0xFFFFFFFFFFFFFFFF (the very edge of memory).
For memory errors like this a good idea is to use a memory checking tool (you can try valgrind memcheck). Now let's see what's wrong with your code :)
The array
You have to take into account that int[m][n] isn't the same as int**. Using the gcc compiler you'll get a warning about it. (Of course, you can alter your code to use int**)
The For Loop
Just as VoteyDisciple said you should be using
for (int j=0;j<m;j++)
instead of
for(int j=0;i<m;j++)
Uninitialized values
Creating an array and not initializing it can lead to memory errors later on (assuming we're talking about C - some languages initialize arrays with 0's). Here you create the x,y,z matrixes but you end up using a portion of them which you assign values to. The rest remain uninitialized and you can end up running into errors if you try accessing them later on.
The scanf exception
Really the exception you get is due to the above, as you're getting errors from trying to access the memory address at &matriz1[i][j]
Fixing it all
Here's how I'd write your code so that it works:
#include <stdio.h>
#include <stdlib.h>
#define num 10
void ler_matriz(int **matriz1, int n, int m);
void mostrar_matriz(int** matriz1, int n, int m);
//int num_min_matriz(int matriz1[][], int n, int m);
//void teste_simetria(int matriz1[][], int n, int m);
//void transposta_matriz(int matriz1[][], int n, int m);
//void soma_matriz(int matriz1[][], int matriz2[][], int matriz3[][], int n, int m);
int main()
{
//int x[num][num], y[num][num], z[num][num], numL, numC;
int i,j,**x,**y,**z,numL,numC; //Proper declarations
x=malloc(num*sizeof(int*));
y=malloc(num*sizeof(int*));
z=malloc(num*sizeof(int*));
for(i=0;i<num;i++) {
x[i]=malloc(num*sizeof(int));
y[i]=malloc(num*sizeof(int));
z[i]=malloc(num*sizeof(int));
}
//Initialization
for(i=0;i<num;i++) {
for(j=0;j<num;j++) {
x[i][j]=y[i][j]=z[i][j]=0;
}
}
printf("Introduza o número de linhas e colunas para a matriz:\n");
scanf(" %d%d", &numL, &numC);
printf("\n\nIntroduza os valores para a matriz 1: ");
ler_matriz(x, numL, numC);
mostrar_matriz(x, numL, numC);
for(i=0;i<num;i++) {
free(x[i]);
free(y[i]);
free(z[i]);
}
free(x);
free(y);
free(z);
return 0;
}
void ler_matriz(int **matriz1, int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("\nx[%d][%d]: ", i + 1, j + 1);
scanf(" %d", &matriz1[i][j]);
}
}
}
void mostrar_matriz(int **matriz1, int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d ", matriz1[i][j]);
}
putchar('\n');
}
}

Why values in 'main' are not changed using pointers?

I have some problems when I use pointers. In this program I want to input a text with ElaboraTesto and after with Sdoppia to put tokens into two different arrays:
StructTesto Pari[] if their length is even.
StructTesto Dispari[] if their length is odd.
Look like it works.
After I use ordinaPari that have to sort tokens according to their length, but when I try to print the array that contains odd tokens, with stampaStruttura, there is no output as well I input odd words.
I try to debug program (see code below) and I saw that vara and varb are always 0.
What am I missing?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DIMMAX 100
typedef char Stringa[DIMMAX];
typedef Stringa TESTO[DIMMAX];
typedef struct{
Stringa parola;
int lunghezza;
} StructTesto;
int ElaboraTesto(TESTO, int);
void Sdoppia(TESTO, int, StructTesto[], int* , StructTesto[], int*);
void stampaStruttura(StructTesto[], int);
void ordinaPari(StructTesto[], int);
void Sdoppia(TESTO t, int l, StructTesto Pari[], int* lp, StructTesto Dispari[DIMMAX], int* ld){
int i;
StructTesto p;
int rest;
int j=0;
int k=0;
ld = &j;
lp = &k;
for(i=0; i<l; i++){
strcpy(p.parola, t[i]);
p.lunghezza = strlen(p.parola);
rest = p.lunghezza % 2;
if (rest != 0){
strcpy(Dispari[j].parola ,p.parola);
Dispari[j].lunghezza = p.lunghezza;
j++;
} else {
strcpy(Pari[k].parola , p.parola);
Pari[k].lunghezza = p.lunghezza;
k++;
}
}
*ld = j;
*lp =k;
}
void stampaStruttura(StructTesto array[], int n){
int i;
for(i=0; i<n; i++){
printf("Parola: %s\n", array[i].parola);
printf("Lunghezza: %d\n", array[i].lunghezza);
}
}
int ElaboraTesto(TESTO t, int n){
char *tokenPtr;
Stringa testo;
int i;
printf("Inserire il testo da elaborare: (MAX %d parole)\n", DIMMAX);
gets(testo);
printf("Il testo che verra' tokenizzato e' il seguente:\n%s\n", testo);
printf("I token sono:\n");
tokenPtr = strtok(testo, " ");
while(tokenPtr != NULL){
printf("%s\n", tokenPtr);
strcpy(t[i], tokenPtr);
tokenPtr = strtok(NULL, " ");
i++;
}
printf("Il testo e' composto da %d parole.\n", i);
return i;
}
void ordinaPari(StructTesto P[], int n){
int i;
StructTesto temp;
for(i=0; i<n; i++){
if(P[i].lunghezza < P[i+1].lunghezza){
temp = P[i];
P[i] = P[i+1];
P[i+1] = temp;
}
}
}
int main(int argc, char *argv[]) {
TESTO testo;
int n;
int dim;
int vara = 0;
int varb = 0;
StructTesto p[DIMMAX];
StructTesto d[DIMMAX];
n = ElaboraTesto(testo, DIMMAX);
Sdoppia(testo, n, p,&vara,d,&varb);
stampaStruttura(p, n);
ordinaPari(p,vara);
stampaStruttura(p, vara);
}
return 0;
}
In the Sdoppia function you have these four lines:
int j=0;
int k=0;
ld = &j;
lp = &k;
The problem with this is that the pointers to the variables in the main function you pass in will be overwritten with the pointers to the local variables j and k.
So when you later do
*ld = j;
*lp =k;
you are actually assigning j to itself and k to itself (i.e. you are simply doing j = j and k = k).
The solution is to not do the initial reassignments to ld and lp.

Function Does nothing

I can't make the function mostrarmatriz() work. The program does compile and run from beginning to end without errors, but the function mostrarmatriz() doesn't show up anything. When I copy that function into the main function it works perfectly. It seems I'm having a problem passing the values by reference. Please help, I'm stuck.
Main.c File:
#include "InvMatriz.h"
#include <stdio.h>
int main(int argc, char **argv)
{
float **A;
int n;
printf("Ingrese el tamaño de la matriz: ");
scanf("%d", &n);
A = ingresematriz(n);
void mostrarmatriz(A, n);
printf("adfasd");
return 0;
}
Header File InvMatriz.h
#ifndef INVMATRIZ_H_
#define INVMATRIZ_H_
float** ingresematriz(int );
void mostrarmatriz(float**X ,int x);
#endif // INVMATRIZ_H
Ingrese Matriz.c File
#include "InvMatriz.h"
#include <stdio.h>
float **ingresematriz(int n)
{
int i, j;
//Asigna espacio en la memoria
float **A;
A = malloc(n * sizeof (float *));
for (i = 0; i < n; i++)
{
*(A + i) = malloc(n * sizeof(float));
}
//Pide los elementos y los guarda
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("Elemento [%d] [%d]: ", i + 1, j + 1);
scanf("%f", *(A + i) + j);
}
}
return A;
}
Mostrar Matriz.c File
#include "InvMatriz.h"
#include <stdio.h>
void mostrarmatriz(float **X , int x) //Porque no hace nada pero si compila?
{
int i, j;
for (i = 0; i < x; i++)
{
for (j = 0; j < x; j++)
{
printf("%f ", *(*(X + i) + j));
}
printf("\n");
}
}
The line
void mostrarmatriz(A,n);
does not call mostrarmatriz, but it declares a function void mostrarmatriz(int,int) (the int type for the arguments is the old "implicit int" rule). Remove the void in that line, and your function will be called.
If you compiled your code with warnings, your compiler would have told you.

Resources