Doubt pointers in C

Asked

Viewed 66 times

1

I have a whole number nI wish to break (separate your digits) and store in a vector, but my code does not work... what I am 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;
}
  • What is the compiler return message? Or what error is happening?

  • added an input and an output

1 answer

1

The problem is here:

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

You’re missing the vector inside the loop. So each time you are re-breaking 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++;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.