1

I had a basic clarification . Here is the code snippet I tried.

void fill(char s[])
{
    strcpy(s,"temp");
}

int main()
{
    char line[100];
    fill(line);
    printf("%s",line);
    return 0;
}

As expected, the output is temp.line is a local array but it can be modified in fill and is reflected back in the caller. My understanding is ,this works because when we say fill(line) we are actually passing the address of start of an array.

Am I correct ?

0

5 Answers 5

3

Yes you are correct.

Note that this is dangerous code - it is very easy with this type of code that fill overwrites the end of the passed-in buffer. Fill should have knowledge of the size of the buffer and should not write past the end of that size.

For example, if instead of writing in "temp" you wrote in the contents of War and Peace, the program would happily overwrite lots and lots of other memory locations not associated with the variable line.

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

Comments

0

Yes, arrays are passed by reference in C.

1 Comment

Nope, everything is passed by value in C. In this case the value just happens to be an address (i.e. a pointer).
0

Yes. In this case the array name decays into a pointer which is then passed to fill.

Comments

0

yes, arrays are passed using their base addresses

Comments

0

Yes. That's correct. If you wanted to explicitly specify the start address, the code would change only slightly. See below: Note the fill function argument is now a pointer.

void fill(char *s)
{
    strcpy(s,"temp");
}

int main()
{
    char line[100];
    fill(line);
    // EQUIVALENT: fill(&line[0]);
    printf("v%s\n",line);
    return 0;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.