Doubt pointers in C

1

I have a whole number n that I want to break (separate your digits) and store in a vector, however my code does not work ... what am I missing?

#define TRUE 1
#define FALSE 0
#define DIM1 3
#define DIM2 3
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<math.h>

int* retorna_quebrado(int a,int &p){

    int* vet;
    int i=0;

    while(a>0){
        vet = (int*) malloc(sizeof(int));
        vet[i]=a%10;
        a=a/10;
        i++;
    }

    p=i;
    return vet;
}

int main(){

    int n;
    int p;
    int* vet = retorna_quebrado(n,p);

    scanf("%d",&n);        

    for(int i=0 ; i<p;i++)
        printf(" \n %d",vet[i]);

    return 0;
}
    
asked by anonymous 19.08.2017 / 20:19

1 answer

1

The problem is here:

while(a>0){
    vet = (int*) malloc(sizeof(int));
    vet[i]=a%10;
    a=a/10;
    i++;
}

You are placing the vector inside the loop. So every time you're re-locating the vector and thus overwriting the content, do so it will work:

vet = (int*) malloc(sizeof(int));

while(a>0){
    vet[i]=a%10;
    a=a/10;
    i++;
}
    
19.08.2017 / 22:09