andx00
andx00

Reputation: 3

changing array in a function c

I was doing some exercises on pointer in C , because I have some problems with them. I have to change some values in an array using a void function , but when I run the code it returns me a segfault. Here's the code :

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

void change( int **v , int l ) {

    for ( int i = 0 ; i < l ; i++ ) 
                 *v[i] = 0 ;

 }

 int main ( int argc , char** argv ) {

           int *v , l ;
           scanf("%d",&l) ;
           v = (int*) malloc(sizeof(int)*l) ;

           for ( int i = 0 ; i < l ; i++ ) 
                    scanf("%d",&v[i]) ;

           change( &v , l ) ;

           for ( int i = 0 ; i < l ; i++ ) 
               printf("%d ",v[i]) ;

           return 0 ;
}

Upvotes: 0

Views: 80

Answers (3)

AleX
AleX

Reputation: 529

Just make your code works, the minimal change of your code is change *v[i] = 0 ; to (*v)[i] = 0 ;

Upvotes: 0

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Try this

#include <stdio.h>
#define MAX 20
typedef int Values[MAX];

int changeArr(int vals2[]) {
    vals2[0] = 200;
    vals2[1] = 100;
    printf("%d and ", vals2[0]);
    printf("%d\n", vals2[1]);
    return 0;
}   

int main (int argc, char *argv[]) {

    Values vals;
    changeArr(vals);
    printf("%d and ", vals[0]);
    printf("%d\n", vals[1]);
    return 0;

}

or

#include <stdio.h>
#define MAX 20
typedef int Values[MAX];

int changeArr(Values *vals2) {
    (*vals2)[0] = 200;
    (*vals2)[1] = 100;
    printf("%d and ", (*vals2)[0]);
    printf("%d\n", (*vals2)[1]);
    return 0;
}   

int main (int argc, char *argv[]) {

    Values vals;
    changeArr(&vals);
    printf("%d and ", vals[0]);
    printf("%d\n", vals[1]);
    return 0;

}

Source : How can I change an int array in a function

Upvotes: 0

ouah
ouah

Reputation: 145829

Change:

void change( int **v , int l )

to

void change( int *v , int l )

then

*v[i] = 0 ;

to

 v[i] = 0 ;

then

change( &v , l ) ;

to

change( v , l ) ;

You don't need to use a pointer to a pointer to int to change an array element, just pass a pointer to the first of the element of the array.

Upvotes: 4

Related Questions