tjjjjjj
tjjjjjj

Reputation: 13

I have an array and I want to pass it into a function then modify it from the function, how can i do that?

Example

//This is my function
void myfunc (how does the definition look like?)
{
int counter = 0;
for (counter = 0; counter < 10; counter++)
{
*arr[counter] += 10;
}

int main(void)
{
char arr[100] = {'\0'};
myfunc (how does this look like?)
return 0;
}

I want to pass in something like a pointer so I can modify it directly from the myfunc()

Upvotes: 1

Views: 40

Answers (3)

Rotem Varon
Rotem Varon

Reputation: 1647

C is not a object oriented language. You have to pass in the size of the array so you will be able to iterate on it safely.

void myfunc (char * arr, int size)
{
   int counter = 0;
   for (counter = 0; counter < size; counter++)
   {
      arr[counter] += 10;
   }
}

int main()
{
   char arr[100] = {'\0'};
   myfunc (arr, 100);
   return 0;
}

Upvotes: 0

myanl
myanl

Reputation: 135

void myfunc (char *s)

and in main function, call as

myfunc (arr);

Upvotes: 1

Barmar
Barmar

Reputation: 781255

When an array is passed to a function, a pointer to the first element is passed.

void myfunc(char *arr) {
    int counter;
    for (counter = 0; counter < 10; counter++) {
        arr[counter] += 10;
    }
}

Upvotes: 3

Related Questions