I'm currently writing a program where the purpose is to send an array of strings to a function, the function will then do a bubble-sort with the array, moving the shorter strings in the array to the front and moving the longer strings to the back so the expected output should be "shortest is cat, longest is elephant".
It seemed straight forward but I'm getting a segmentation fault and I've looked over the indexes of the code but it doesn't seem to go out of bounds so im not sure whats happening. Here is my example code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fx(char* array[],int size);
int main()
{
char* t[]= {"horse","elephant","cat","rabbit"};
int n;
n = sizeof(t)/ sizeof(t[0]);
fx(t,n);
printf("shortest is %s, longest is %s\n",t[0],t[n-1]);
}
void fx(char* array[],int size)
{
int i;
int current,next,unsorted;
char* stringTemp;
do {
unsorted = 0;
for(i = 0; i < size-1; i++)
current = strlen(array[i]);
next = strlen(array[i+1]);
if( current > next )
{
stringTemp = array[i];
array[i] = array[i+1];
array[i+1] = stringTemp;
unsorted = 1;
}
}
while(unsorted);
}
also a quick question regarding strings. Earlier when i stared i stored the strings in char array[] but i got errors saying maximum declaration reached or something similar. Was that something i did or can you not store strings in a char array like that?
for()clause and a matching curly between the other two closing ones.-gflag to gcc) and run in a debugger. The debugger will stop where the crash happens, and let you examine the call stack. If the crash is not in your code you can walk up the stack until you end up at your code, and there you can examine the values of variables. At least edit your question to include the call stack from the debugger.