So I input strings into an array mydata[10][81]
while ((ct<=10) && gets(mydata[ct]) != NULL && (mydata[ct++][0] != '\0'))
I then use a for loop to create a second array of pointers
for (i=0;i<11;i++){
ptstr[i] = mydata[i];
}
This is where I get stuck
I know I need to use strlen
somehow, but I can't even conceive of how to get the length of a pointer and then re-assign that pointer a new position based on a third additional value of length
Hopefully that makes sense, I'm so lost on how to do it or explain it, I'm just trying to sort strings by length using array positions (not using something like qsort
)
I did some more work on it and came up with this: any idea why its not working?
void orderLength(char *ptstr[], int num){
int temp;
char *tempptr;
int lengthArray[10];
int length = num;
int step, i, j, u;
for (i=0; i<num;i++){
lengthArray[i] = strlen(ptstr[i]);
}
for (step=0; step < length; step++){
for(j = step+1; j < step; j++){
if (lengthArray[j] < lengthArray[step]){
temp = lengthArray[j];
lengthArray[j] = lengthArray[step];
lengthArray[step] =temp;
tempptr=ptstr[j];
ptstr[j]=ptstr[step];
}
}
}
for (u=0; u<num; u++){
printf("%s \n", ptstr[u]);
}
}
qsort
and a custom comparator based onstrlen
. – Arterioleqsort
library function. Or read more about sorting algorithms. – Brindabrindellstrcmp
to compare the contents. If you're sorting them by length, you compare the lengths instead (compare the values returned bystrlen
) – Laheymystrings[10][81]
but thenfor (i=0;i<11;i++) ptstr[i] = mystrings[i];
which will exceed the array bounds. Change tofor (i=0;i<10;i++)
. I strongly advise on the use of#define
to set array and other sizes, i.e. don't "hard code" every individual statement. One upshot is you can alter the limit / size if necessary in one stroke. – Deconsecrategets()
. – Serializestrlen
is for comparing strings.strlen
yields numbers. There is no standard function for comparing numbers, but look at Nit's answer bbewlo, which implements a suitable comparison function. – Lacteal