1

i've try to compile this simple program, it will alloc a dyamic array and return it with a multiple of 5 in every location. but it doesn't work, it report me an error in the pointer.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[]) {
    int n;
    int i;
    int* ptra;
    scanf("%d", &n);
    ptra = malloc(n*(sizeof(int)));

    for(i=0; i<=n; i++){
        ptra[i] = (5*(i+1));
        printf("%d\n", ptra[i]);
    }
    return 0;
}
12
  • Indent your code please. Commented Nov 30, 2016 at 10:34
  • An array of n integers contains elements in the range from 0 to n - 1. Now take a look at your loop again, and think about that loop condition. Commented Nov 30, 2016 at 10:35
  • it should be for(i=0;i<n;i++) Commented Nov 30, 2016 at 10:36
  • 1
    Please elaborate on "doesn't work". If it doesn't build then please include the build errors. If it crashes then use a debugger to locate where in your code it happens. If you get unexpected output then include the input and the expected and actual output. Commented Nov 30, 2016 at 10:43
  • 1
    In that case I think you should delete the question, as it's not really useful in its current form. Commented Nov 30, 2016 at 10:50

2 Answers 2

3

Index range for ptra must be from 0 to n-1 (both inclusive). But here:

for(i=0;i<=n;i++){

you are going out of bounds, which is undefined behaviour. Change it to:

for(i = 0; i < n; i++) {

Note: Always check the return of all the standard functions for failures (scanf() and malloc() in your code).

Sign up to request clarification or add additional context in comments.

3 Comments

Did you add the error checking I suggested? Please describe what "doesn't work". It works as expected.
the compiler compile the program, but when i'm going to run it,report me "the program It is not recognized as executive program or a batch file"
That appears to a problem with your environment. Check your PATH is correct. See this and related posts linked in that page.
0

Your for loop is going one step beyond the limit: must go as long as i<n and not i<=n

try doing:

for(i=0; i<n; i++){

1 Comment

it report me "the program It is not recognized as executive program or a batch file"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.