Member Avatar for RenFromPenn

Hi,

I am trying to change the address in an array using *nums++. When I run the program, however, the first number in the array is skipped. What am I missing? How do I get the first number to display?

#include <stdio.h>
int print(int[]);


int main()
{
	#define NUMBERS 7
	int nums[] = {2, 4, 5, 7, 9, 11, 13};

	print(nums);

	return 0;
}

int print (int *nums)
{
	int i;
	i = *nums++;

	for (i = 1; i < NUMBERS; i++, nums++)
	printf("Address %d contains number %d\n", i, *nums );

return 0;

}

> i = *nums++;
Well this does nothing, except to skip the first entry of the array.
You lose i in the following assignment in the for loop.

>What am I missing? How do I get the first number to display?

Move #define NUMBERS 7 outside of main so the function print can see it.
In print() remove i= *nums++ which is doing harm and producing nothing since you change the value of i inside the loop to start at 1 anyway.

Not to be picky, but #define NUMBERS is a pre-processor directive and doesn't get scope.

(But it should have been outside the function anyway.)

commented: Correct +12
Member Avatar for RenFromPenn

Move #define NUMBERS 7 outside of main so the function print can see it.
In print() remove i= *nums++ which is doing harm and producing nothing since you change the value of i inside the loop to start at 1 anyway.

I tried this and now I have the opposite problem. The last number doesn't print. Suggestions?

>I tried this and now I have the opposite problem. The last number doesn't print. Suggestions?

start i in the loop at 0 or stop it when is < or equal to NUMBERS

Member Avatar for RenFromPenn

start i in the loop at 0 or stop it when is < or equal to NUMBERS

Thanks! < or equal did just what I wanted.

see what i have made changes in u r program

#include <stdio.h>
int print(int[]);


int main()
{
    #define NUMBERS 7
    int nums[] = {2, 4, 5, 7, 9, 11, 13};

    print(nums);

    return 0;
}

int print (int *nums)
{
    int i;
    i = (*nums)++;

    for (i = 1; i <= NUMBERS; i++, nums++)
    printf("Address %d contains number %d\n", i, *nums );

return 0;

}

somnathsarode if you are going to post code, especially in response to a thread, please use the appropriate code tags.

For this forum:
[code=c] /* your code goes here */

[/code]

Your response followed the original poster saying "Thanks ... did just what I wanted." Almost seems like the thread was answered doesn't it.

Member Avatar for RenFromPenn

Well, since I am the original poster, I can say that my question was answered. I was just about to ask if there was a way to mark this as solved when I looked up and saw it right above this box. Sorry I didn't mark it previously. I'm new hear and still learning how the forum works. :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.