Hey guys thanks very much for your input. My prof does brackets like
but I see a lot of code on these forums look like the following so I adapt them that way (plus its easier to make sure your syntax is correct)
BUT, I have one more issue guys which I would really love your help on. After resubstituting the corrections in my program doesn't display the sorted words...at all...the program comes to a halt with this code ;
(really sorry for the eye sore, don't have time to tidy it up)
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char **p;
char size[20];
char buff[21];
char temp[21];
int N;
int j,i,k,l,m,d,s,a,b;
int main()
{
do{
d=0;
printf("How many words would you like: ");
fflush(stdout);
for(j=0; j<20; j++)
{
size[j]=fgetc(stdin);
if (size[j]=='\n')
{
size[j]='\0';
break;
}
}/* end j-loop */
if (j==0){
printf("That input is empty.\n");
d=1;
}
if (j==20) {
printf("That input is too long.\n");
while(fgetc(stdin)!='\n');
d=1;
}
}while(d!=0);
printf("You want %d words.\n", atoi(size));
N=atoi(size);
p=(char**)malloc(N*sizeof(char*));
if (p==NULL)
{
printf("Memory error");
exit(0);
}
for (i=0; i<N; i++)
p[i]=(char*)malloc(21*sizeof(char));
if (p[i]==NULL)
{
printf("Memory error");
exit(0);
}
printf("Do not enter more than 20 characters.\n");
for(k=0; k<N; k++)
{
A:printf("Enter a word: ");
fflush(stdout);
for(m=0; m<21; m++)
{
buff[m]=(char)fgetc(stdin);
if (buff[m]=='\n')
{
buff[m]='\0';
break;
}
}
if (m>=21)
{
printf("Word is more than 20 characters.\n");
while(fgetc(stdin)!='\n');
goto A;
}
if (m==0)
{
printf("That input is empty\n");
goto A;
}
strcpy(p[k],buff);
}
printf("\n");
printf("Your unsorted list of Names:\n");
k=0;
for(k=0; k<N; k++)
printf("%s\n",p[k]);
for (a=N; a>0; a--)
{
for (b=0; b<a; b++)
{
if(strcmp(p[b],p[b+1])>0)
{
strcpy(temp,p[b]);
strcpy(p[b],p[b+1]);
strcpy(p[b+1], temp);
}
}
}
printf("\n");
printf("Your sorted list of Names:\n");
k=0;
for(k=0; k<N; k++)
printf("%s\n",p[k]);
return 0;
}
The program just...stops at "Your sorted output is :" and you have to CTRL + break to get out of it.
When N (the number of words they want) is 0 -zero- the "sorted" output is a smiley face...lol does that point out what I am doing wrong?
The code provided by my professor was;
Code:
if(strcmp(p[b],p[b+1])>0)
{
temp=p[b];
p[b]=p[b+1];
p[b+1]=temp;
}
Basically he illustrated it as changing the location of the pointers (which makes sence) however using that code gives me Lvalue issues(which I don't know what that error means).