0

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 ;
}
2
  • The reason for using as an argument int **v What? Commented Dec 15, 2013 at 15:28
  • *v[i] --> (*v)[i] Commented Dec 15, 2013 at 15:31

3 Answers 3

4

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.

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

Comments

0

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

Comments

0

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

Comments

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.