Indirection

This is a discussion on Indirection within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> using namespace std; void changevalue(int *value); main() { int value[10]; changevalue(value); for(int x=0; x<10; x++) { cout<<value[x]<<endl;//why ...

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    70

    Indirection

    Code:
    #include <iostream>
    using namespace std;
    void changevalue(int *value);
    main()
    {
    	int value[10];
    	changevalue(value);
    	for(int x=0; x<10; x++)
    	{
    		cout<<value[x]<<endl;//why does this line work...
    	}
    	return 0;
    }
    void changevalue(int *value)
    {
    	for(int x=0; x<10; x++)
    	{
    		value[x]=x+1;
    	}
    }
    i commented a line...why does that work, when this also works..
    Code:
    #include <iostream>
    using namespace std;
    void changevalue(int *value);
    main()
    {
    	int value[10];
    	changevalue(value);
    	for(int x=0; x<10; x++)
    	{
    		cout<<*value;//why the need for indirection?
    	}
    	return 0;
    }
    void changevalue(int *value)
    {
    	for(int x=0; x<10; x++)
    	{
    		value[x]=x+1;
    	}
    }
    why do i need indirection for value (*value) but when i call it as an element from the array, there is no need for the indirection. as in, why does this not work, but the second portion of code does.
    Code:
    #include <iostream>
    using namespace std;
    void changevalue(int *value);
    main()
    {
    	int value[10];
    	changevalue(value);
    	for(int x=0; x<10; x++)
    	{
    		cout<<*value[x]<<endl;//error
    	}
    	return 0;
    }
    void changevalue(int *value)
    {
    	for(int x=0; x<10; x++)
    	{
    		value[x]=x+1;
    	}
    }
    Thanks.

  2. #2
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    value[x] is a variable. (An integer).
    value is a pointer to value[0]. (An address).

    This makes dealing with string arrays easier, because you often can pass the pointer to a string (or any array) to a function.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C2100 Illegal Indirection error?
    By dnguyen1022 in forum C++ Programming
    Replies: 1
    Last Post: 06-18-2009, 10:47 PM
  2. Replies: 8
    Last Post: 06-04-2009, 02:03 PM
  3. NAQ: Everything you never wanted to know about CPP
    By evildave in forum C Programming
    Replies: 21
    Last Post: 12-12-2005, 09:56 AM
  4. indirection error
    By Eber Kain in forum C++ Programming
    Replies: 1
    Last Post: 02-10-2002, 11:06 PM
  5. Levels of Indirection???
    By Garfield in forum C Programming
    Replies: 6
    Last Post: 09-11-2001, 02:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21