You are not logged in. Please login at www.codechef.com to post your questions!

×

what is problem with this code .Please expain?

#include<iostream>

using namespace std;

int main()
{
    int *p;
    for(int i=0;i<10;i++)
    {
        cout<<"enter value for element ";
        cin>>*p;
        p++;
    }
    for(int i=0;i<10;i++)
    {
        --p;
        cout<<"\nenter value for element "<<*p;
    }
    return 0;
}

asked 28 Sep '13, 22:48

anu1234's gravatar image

1★anu1234
11431018
accept rate: 0%

edited 29 Sep '13, 09:43

tijoforyou's gravatar image

2★tijoforyou
4.2k52364


The only problem with your code is that you have just declared a pointer, but that pointer is not pointing to any location i.e it has not been allocated any space.

If you want to use the pointer to be used in place of an array, you have to allocate it enough space on the heap.

In the above case

//size of array 10 *p = (int *)malloc(10*sizeof(int)) // c implementation, Don't forget to include cstdlib *p = new int[10] // c++ implementation

This would solve your problem.

P.S. Casting the void pointer returned by malloc is a bad practice and is not recommended.

link

answered 28 Sep '13, 23:51

vinitkp's gravatar image

4★vinitkp
55235
accept rate: 0%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×2,718

question asked: 28 Sep '13, 22:48

question was seen: 965 times

last updated: 22 Aug '16, 02:14