0

What is the difference between sending a string directly than sending a pointer to a string to a function?

For example:

void foo(char * a){//suppose foo reads and/or writes to the passed string
    ...
}

int main(){
    foo("asdf");//what is the difference between this

    char a[]="asdf";
    foo(a);//and this?
}

With the first I'm getting all sorts of access violation errors while with the second I don't, so what is the difference between the two?

shinzou
  • 5,850
  • 10
  • 60
  • 124
  • Does your foo() function currently do anything to the string that is passed in? – Daniel Feb 19 '15 at 12:09
  • The second case copies the values onto the stack at runtime. The first doesn't. The call to foo in the first case passes an address from the BSS (or wherever static data exists on your platform), and the second passes an address on the stack. – William Pursell Feb 19 '15 at 12:09
  • @Daniel suppose it reads and/or write to the string. – shinzou Feb 19 '15 at 12:10

2 Answers2

5

In the first case, you pass a string literal to the function. String literals are immutable meaning that you cannot change any part of it. This, is a static array stored in read-only memory segment. Attempting to alter this string results in Undefined Behavior.

In the second case, you construct an array, initialize it with "asdf" and pass it to the function. In this case, the characters in the array can be modified.

See question 1.32 of the comp.lang.FAQ for more info.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
1

First of all you should know that there is no string in C and therefore no pointer to string but pointer to char array is possible.

The code snippet

foo("asdf");  

is equivalent to

char a[]="asdf";
foo(a);  

because in C, string literals are of type char [] and hence no difference in in both of the snippet except that you can't modify a string literal passed in foo("asdf"); inside foo function unlike in second snippet.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264