Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am stuck with this program can someone help me out with this programme

What I have tried:

C#
//dynamic memory allocation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
	{
		int s, i,*p,*ptr,*q,sum=0;
		printf("enter the count for numbers to input\n");
		scanf("%d",&s);
		ptr=(int*)malloc(sizeof(int)*s);
		p=ptr;
		printf("memory allocated %u\n",ptr);
		if(ptr==NULL)
		{
			printf("out of memory\n\n");
			exit(0);
		}
		printf("enter %d elements\n",s);
		for(i=1;i<=s;i++)
		{
			scanf("%d",ptr);
			sum=sum+*ptr;
			ptr++;
		}
		printf("............displaying elements........\n");
		for(i=1;1<=s;i++)
		{
			printf("%d\n",*p);
			p++;
		}
		printf("addition is =%d\n",sum);
		printf("enter the new count for the number to input\n");
		scanf("%d",&s);
		ptr=(int*)realloc(ptr,s*sizeof(int));
		q=ptr;
		if(ptr==NULL)
		{
			printf("out of memory\n");
			exit(0);
		}
		printf("reallocated memory is: %u\n",ptr);
		printf("enter %d elements\n",s);
		for(i=1;i<=s;i++)
		{
			scanf("%d",ptr);
			sum=sum+*ptr;
			ptr++;
		}
		printf("..............displaying the elements..........\n");
		for(i=1;i<=5;i++)
		{
			printf("%d\n",*q);
			q++;
		}
		printf("addition is:  %d\n",sum);
		getch();
		return 0;
	}
Posted
Updated 26-Oct-16 15:07pm

With C/C++ array indexes are zero based (valid indexes are in the range from 0 to number of items minus one).

So you have to change your loops:
C++
/* This is wrong: */
/* for(i=1;i<=s;i++) */
/* This is correct: */
for(i=0;i<s;i++)
{
    scanf("%d",ptr);
    sum=sum+*ptr;
    ptr++;
}

Your code does not use the first element but accesses an element beyond the size of the array (out of bounds access). Doing so leads to unpredictable behaviour.
 
Share this answer
 
*** Unable to leave this as a comment ***

Did you want to describe the problem you're having? Without it, you're not going to get an answer let alone an accurate answer.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900