Thread: string array stuck:(

  1. #16
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    Code:
    scanf("%d",&num);
    char no[num][50],name[num][50],sur[num][50];
    This is very illegal - the reason why is because if you are declaring
    an array in C, the dimensions need to be constant at compile
    time (static memory allocation). If you don't know the dimensions
    at compile time, malloc must be used (the dynamic in dynamic
    memory allocation), you cannot do it in this manner. Should look
    like this:

    char no[10][50];

    Also I'm getting errors for not having all variable declarations
    at the start of the code block - i thought that this was changed
    in the last C standard, but in case it wasn't and Visual Studio
    is correct, move those lines directly under main(){...

    Code:
    printf("ID: ");
                          scanf("%s",&no[k][0]);
    
                          scanf("%s",&name[k][0]);
    
                          scanf("%s",&sur[k][0]);
                          k++;
    very wrong as well - scanf takes the memory address of where
    it is reading in to, but when dealing with strings it should just
    take the name of the string it is reading into. what you have
    set it up to do is read it into the kth row of the 0th column - a
    single element within the array. because scanf does't do
    bounds checking it keeps on reading into the 1st, 2nd columns
    and so on. Normally this would crash your program but since
    you declared arrays it is operating, but its not working correctly
    to say the least. these lines of code should be as follows:

    Code:
    printf("ID: ");
                          scanf("%s", no[k]); /*notice no &?*/
    Ideally you should be using fgets to read in strings anyway.

    >>my compiler did not encountered any errors
    That surprises me - dev-cpp should throw a fit at the array declarations - too lazy to try, but trust me - that code was very
    wrong. It wouldn't complain about not declaring variables at
    the start of main because you probably have the file saved
    as .cpp - in C++ it would be legal, but as I said it may/may not
    be legal in C.

    Also, do you realise that your case 2 does its work in a very
    ugly way - printf can print whole strings using %s - you don't
    need to loop and print every character individually

    On another note, your code indentation is very inconsistent and
    it makes it very awkward to read. To that end, I've beautified it
    and reposted it below. I've made the changes that make it work
    properly and introduced some improvements.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #define NUM 5
    
    /*The above allows for arrayname [NUM] because the program knows NUM is always 5*/
    /*This means that the compiler will create an array of 5*/
    
    int main(void)
    {
    	int choice = 0;
    	int k = 0, l = 0;
    	int a1[NUM];
    
    	float res = 0;
    
    	char no[NUM][50], name[NUM][50], sur[NUM][50];
    
    	printf("\n 1. Student registration.\n"
    	" 2. List of course.\n"
    	" 3. Enter final results.\n"
    	" 4. Show average of final results.\n"
    	" 5. Exit\n");
    
    	while(choice!=5)
    	{
    		printf("your choice:");
    		scanf("%d",&choice);
    		switch(choice)
    		{
    
    		case 1:
    			while(k<NUM)
    			{
    				printf("ID: ");
    				scanf("%s",no[k]);
    				printf("Name: ");
    				scanf("%s",name[k]);
    				printf("Surname: ");
    				scanf("%s",sur[k]);
    				k++;
    			}
    			break;
    
    		case 2:
    			printf("\n");
    			printf("ID\tName\tSurname\n");
    			
    			do
    			{
    				printf("%s",no[l]);
    				printf("\t");
    				printf("%s",name[l]);
    				printf("\t");
    				printf("%s",sur[l]);
    				printf("\n");
    				l++;
    			}while(l<NUM);	/*a for loop would work well here instead of do-while*/
    			l = 0; /*output is scrambled if you choose case 2 twice - this repairs it*/
    			break;
    
    		case 3:
    			for(l=0;l<NUM;l++)
    			{
    				printf("%s:",name[l]);
    				scanf("%d",&a1[l]);
    			}
    			l = 0; /*as above*/
    			break;
    
    		case 4:
    			for(k=0;k<NUM;k++)
    			{
    				res=res+a1[k];
    			}
    			k = 0; /*as above again*/
    			
    			res=res/(float)NUM;
    			printf("average : %.2f\n",res);
    			res = 0.0; /*again as above*/
    			break;
    
    		case 5:
    			exit(1); /*this is a bit redundant since entering 5 should quit anyway*/
    		}     
    	}
    
    	return 0;
    }
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  2. #17
    Registered User
    Join Date
    May 2006
    Posts
    20
    Youre right about scanfs and my way of printing strings. Maybe I should blame my compiler there were no errors and when I erase the & and the column part of my multi arrays the program worked as well.
    I mean:
    Code:
    scanf("%s",no[k]);//I understand its not the right way but "scanf("%s",&no[k][0]);" does the same job for my compiler?!...
    Its also same for printf statements and
    Code:
    printf("%s\n",&no[l][0]);// and printf("%s\n",&no[l][0]); are same also or printing in a loop with "%c"...
    I will install visual c and use it from now on. And also the code is compiled as .c file not .cpp!

    For the memory allocation subject, the point why I had to declare arrays inside a switch and did not put static dimension is:
    I MUST take the dimension as an input from the "user". And I seek a way to do it without using malloc() function. So I should really change my compiler program. Any suggestions?

    note for Richie T: do not take it personal but may I kiss you for your efforts to teach me the proper C language(I really thank you and appreciate)!:P

    note for everyone: I am straight, go away!
    Last edited by mass; 05-22-2006 at 01:54 PM.

  3. #18
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Richie T
    Code:
    scanf("%d",&num);
    char no[num][50],name[num][50],sur[num][50];
    This is very illegal - the reason why is because if you are declaring
    an array in C, the dimensions need to be constant at compile
    time (static memory allocation). If you don't know the dimensions
    at compile time, malloc must be used (the dynamic in dynamic
    memory allocation), you cannot do it in this manner. Should look
    like this:

    char no[10][50];
    Well actually, you can do it that way. C99 allows for mixing declarations throughout your code as well as arrays whose size aren't known until run time. However, there are very few (1?) fully C99 compliant compilers out there. Most of them that support C99 only support a few of its "features".


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #19
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    >>Maybe I should blame my compiler there were no errors

    Visual didn't complain about the scanfs because compilers will only
    do so much to avoid errors. There's nothing wrong with dev, its
    just you might want to look into increasing the error checking it
    does - look at compiler options. As Salem said, its built around the
    gcc compiler so if you look at his compiler o/p you can see the
    extra instructions that he passed to the compiler (-W -Wall -ansi -
    pedantic -O2 ) - they might be a little different for dev but they
    can be passed to it as well.

    >>does the same job for my compiler?!...

    As Salem regularly puts it "another person who learns works for
    me C as opposed to standard C" (or something along those lines).
    You need to understand why that code was wrong - also why
    you shouldn't use scanf for reading in strings - its about as bad
    as gets - I'd go so far as to say that its worse because it stops
    reading at whitespace. As far as the printf goes - thats a matter
    of choice - a stupid choice in my opinion since it involves
    unnecessary loops, but hey its your program!

    >>without using malloc()

    you've probably seen quzah's statement - you will be pleased to
    learn that the lastest code that I provided can very easily be
    modified to use malloc. Its up to you. If you were going that
    road, I would suggest practicing 2-d array allocation in a separate
    program so you can get comfortable with the syntax involved -
    then you will be able to adapt the program more easily as
    opposed to messing with the current working code.

    >>I had to declare arrays inside a switch

    Well no. what I was saying was to do the allocation at the start
    (ask for the dimensions at the start) and THEN enter the loop,
    using only one memory allocation, and one deallocation - there was
    no need to ask for the number of records inside in a loop where
    repeated calls to malloc would be assigned to the same pointer -
    each repeated time you choose that option that does the
    allocation you trash the memory you allocated the previous time
    (sorry if thats a little convoluted sounding).

    >>I really thank you and appreciate

    Your welcome - i help when I can, and it often results in improving
    my own understanding of a concept, or learning something new
    (as per quzah's post).
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  2. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM