0
I’m refactoring my code to make it more dynamic, but by including the line int n = sizeof(vetor)/sizeof(int);
within the function bubble
it has failed to function properly. Where am I missing?
Modified Code
void bubble(int vetor[])
{
int n = sizeof(vetor)/sizeof(int);
int k = n;
int aux;
for(int i=0; i<n; i++)
{
for(int j=0; j<k; j++)
{
if(vetor[j]>vetor[j+1])
{
aux=vetor[j];
vetor[j]=vetor[j+1];
vetor[j+1]=aux;
}
}
k--;
}
}
int main()
{
int vetor[]={10,3,5,8,1,9,2,4,7,0,6,-1};
int n=sizeof(vetor)/sizeof(int);
bubble(vetor);
printf("\n\n\n");
for(int i=0;i<n;i++)
{
printf("%d\n",vetor[i]);
}
printf("\n\n\n");
system("pause");
return 0;
}
Original Code
void bubble(int vetor[],int n)
{
int k = n;
int aux;
for(int i=0; i<n; i++)
{
for(int j=0; j<k; j++)
{
if(vetor[j]>vetor[j+1])
{
aux=vetor[j];
vetor[j]=vetor[j+1];
vetor[j+1]=aux;
}
}
k--;
}
}
int main()
{
int vetor[]={10,3,5,8,1,9,2,4,7,0,6,-1};
int n=sizeof(vetor)/sizeof(int);
bubble(vetor,n);
printf("\n\n\n");
for(int i=0;i<n;i++)
{
printf("%d\n",vetor[i]);
}
printf("\n\n\n");
system("pause");
return 0;
}
Victor, thank you for the information regarding the use of sizeof. I didn’t know about this problem that may occur.
– Kelly Soares