Thread: How to use pointers in this case?

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    19

    Question How to use pointers in this case?

    I have the following code
    Code:
    #include <stdio.h>
    
    typedef struct
    {
    	char nume[60];
    	char sectie[20];
    	int grupa;
    } student;
    
    int schimb (student *faculta)
    {
      faculta[1]->grupa=6;
    return 0;}
    
    int main()
    {student faculta[3];
      faculta[1].grupa=5;
      schimb(&faculta[1]);
      printf("%d",faculta[1].grupa);
    return 0;}
    the code shell only change the value of faculta[1].grupa using the function schimb.
    How can I make this code work ?

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Code:
    #include <stdio.h>
    
    typedef struct 
    {
    	char nume[60];
    	char sectie[20];
    	int grupa;
    } student;
    
    void schimb (student *faculta)
    {
    	faculta->grupa = 6;
    }
    
    int main( void )
    {
    	student faculta[3];
    
    	faculta[1].grupa=5;
    
    	
    	printf("Before: %d\n",faculta[1].grupa);
    	schimb(&faculta[1]);
    	printf("After:  %d\n",faculta[1].grupa);
    
    	return 0;
    }
    What you passed into the function was one value of the array. Not an array in itself. I also did some formatting ... makes it look nicer.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    How can I make this code work ?
    What do you want to do?

  4. #4
    Registered User
    Join Date
    Jan 2007
    Posts
    19
    Quote Originally Posted by 7stud
    What do you want to do?
    Ok and how do I pass into the function the whole array and not only a value of the array ?

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Code:
    void display( int arr[], int length)
    {
    	for(int i = 0; i < length; ++i)
    	{
    		cout<<arr[i]<<" ";
    	}
    	
    	cout<<endl;
    }
    
    
    int main()
    {
    	const int SIZE = 3;
    	int myArray[SIZE] = {10, 20, 30};
    	display(myArray, SIZE);
    
            return 0;
    }
    Last edited by 7stud; 01-14-2007 at 08:23 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reducing Code size from ridiculous length
    By DanFraser in forum C# Programming
    Replies: 10
    Last Post: 01-18-2005, 05:50 PM
  2. Keypress reading
    By geek@02 in forum Windows Programming
    Replies: 1
    Last Post: 06-16-2004, 12:16 PM
  3. Xmas competitions
    By Salem in forum Contests Board
    Replies: 88
    Last Post: 01-03-2004, 02:08 PM
  4. rand()
    By serious in forum C Programming
    Replies: 8
    Last Post: 02-15-2002, 02:07 AM