简体   繁体   中英

Can't access the memory location in an array without printing the contents of the array

I am a newbie to C, thus I am not very good with pointers or the concept of handling memory locations. My goal is to make a function in C to slice an array, given the array itself and the starting and ending index. I am aware of alternatives to my implementation, but I am clueless as to why my code is not working.

#include <stdio.h>

int* slice(int arr[], int first, int last) {
    int new_arr[last - first];
    int* p;
    p = new_arr;
    int i;
    int j;

    i = first;
    j = 0;

    while (i < last) {
        new_arr[j] = arr[i];
        // printf("From slice: %d\n", arr[i]);
        i++, j++;
    }

    return p;
}

Below is the function that I used to call slice and then print out the contents of the new array.

int main() {
    int test_arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int first_index = 0;
    int last_index = 4;
    int* x = slice(test_arr, first_index, last_index);

    size_array = last_index - first_index;

    for (int i = 0; i < size_array; i++) {
        printf("From main: %d\n", *(i + x));
    }

    return 0;
}

The problem with my code is that when I uncomment the print statement in the slice function, I get the the array that x points to contains the values 1, 2, and 3 , but when I keep it commented the function doesn't work. From my knowledge, a print statement should not affect the results.

Output with print statement in slice :

From slice: 1
From slice: 2
From slice: 3
From main: 1
From main: 2
From main: 3

Output without print statement in slice :

From main: 1
From main: 0
From main: 0

Returning pointers to non-static local arrays is a bad idea because they are invalidated on returning from the function and therefore returned pointers are useless.

If you want to return a reference to the original array, you can return a pointer pointing at the original array:

int* slice(int arr[], int first, int last) {
    return arr + first;
}

If you want to return copy of an array, you can dynamically allocate memory:

#include <stdlib.h>

int* slice(int arr[], int first, int last) {
    int i;
    int* new_arr = malloc(sizeof(*new_arr) * (last - first));
    if (new_arr == NULL) return NULL;
    for (i = 0; first + i < last; i++) {
        new_arr[i] = arr[first + i];
    }
    return new_arr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM