Issue with managing pointer to int array

时间:2015-06-30 13:39:32

标签: c pointers

I'm having some problem with my code, it crashes when I enter the value of n.

I have entered what I think the code should do.

I guess there is an issue with the pointer to *a[i] which cause the program to crash.

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


void assign_zero(int * a[], int * n){ // fetches value of a and n
    int i;
    for (i = 0; i < *n; i++)
        *(a)[i] = 0; // puts every value in the array to 0 (a[3] = {0,0,0,0})
}

int main(){
    int n;

    printf("Choose value of n: ");
    scanf("%i", &n); // stores the int at n's adress
    int a[n]; // sets the length of the array

    assign_zero(&a, &n); // sends the adress of a and n to assign_zero

    int x;
    for (x = 0; x < n; x++)
    printf("%i", a[x]); // prints 00000... depending of n's value

    return 0;
}

3 个答案:

答案 0 :(得分:3)

In your call, you're using

 assign_zero(&a, &n);

call. But the function signature is

void assign_zero(int * a[], int * n)

which seems wrong in this case. You only need a pointer, to hold the passed array, like

 void assign_zero(int * a, int * n)

will suffice. Then, in the function, you can directly use a[i] to access the elements of the array.

That said, it seems you're not modifying the value of n from assign_zero() function. If that is the case, you don't need to pass it as a pointer.

答案 1 :(得分:2)

Too many *'s! Try this...

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


void assign_zero(int * a, int n){ // fetches value of a and n
    int i;
    for (i = 0; i < n; i++)
        a[i] = 0; // puts every value in the array to 0 (a[3] = {0,0,0})
}

int main(){
    int n;

    printf("Choose value of n: ");
    scanf("%i", &n); // stores the int at n's adress
    int a[n]; // sets the length of the array

    assign_zero(a, n); // sends the address of a and n to assign_zero

    int x;
    for (x = 0; x < n; x++)
    printf("%i", a[x]); // prints 00000... depending of n's value

    return 0;
}

You don't need to pass the address of n into assign_zero as you don't modify it within the function.

And any pointer is implicitly (and possibly dangerously) the base address of an array. That is to say you can index any pointer with square brackets, therefore you only need a to be declared a pointer to int.

答案 2 :(得分:1)

You don't need to pass the addresses of the variables at all, if you redefine assign_zero like this

void assign_zero(int *a, int n)
{
    for (int i = 0; i < n; i++)
        a[i] = 0;
}

it would work fine if you call it like

printf("Choose value of n: ");
if (scanf("%i", &n) == 1) /* never ignore the return value of any function, NEVER */
{
    int a[n];
    assign_zero(a, n);

    for (int x = 0 ; x < n ; x++)
        printf("%i", a[x]);
}

but the assign_zero function is completely unnecessary, you can just

#include <string.h>

and then

memset(a, 0, sizeof(a));