tina
tina

Reputation: 101

Passing character arrays in C++

While passing a character pointer used to reference a string by its address (i.e. directly via its name or &name[0]) the original string must get passed, since we are passing by address.

However, after executing the following code, I got two different values of address for the first element, which, surprisingly, are 2 bytes apart.

Also, modifying the contents of the string in the function, didn't change the content of the array passed, but this is because a new string will have generated a new address, right?

But about the address of the first element being different, how is that possible?

#include<conio.h>
#include<stdio.h>
#include<iostream.h>

void fn(char *arr)
{
    cout<<endl<<&arr;
    arr="hi";
}

void main()
{
    clrscr();
    char *arr="hey";
    cout<<endl<<"main "<<&arr;//the address is different from that in fn
    fn(arr);
    cout<<endl<<arr;
}

Upvotes: 0

Views: 218

Answers (2)

James Fremen
James Fremen

Reputation: 2290

Just an FYI. I was unable to comment on a similar question about passing character arrays because it was closed as a duplicate, but the issue is fairly important so hopefully you don't mind if i cross-post.

When using strings in a production application you usually go with UTF-8 because it significantly increases the market without a lot of effort.

http://www.joelonsoftware.com/articles/Unicode.html

Most applications also use a string class to encapsulate the characters. Then you can use something like:

void fn(..., const std::string &static_string, ...);

in your header. If you use a library like gettext, your code looks like:

printf(gettext("and suddenly there's one line which is good.."));

where the english strings act as intuitive indices into localization files and you can rapidly and easily switch languages at install or runtime.

If you can't use a class because you're using C then the gettext docs cover this case as well.

Upvotes: 0

You are passing a pointer by value, and then comparing the address of the pointer and the copy, which of course differ. If you want to check that they point to the same memory address you can do that:

std::cout << (void*)arr << std::endl;

modifying the contents of the string in the function, didnt change the content of the array passed

You are not modifying the contents of the string, but rather reassigning the copy of the pointer to point to a different string literal. Also note that modifying the pointed memory (the literal) would be undefined behavior.

The only reason that the compiler let the code through (i.e. compiled it) is that there is a backwards compatibility feature that allows you to have a char* that points to the contents of a string a literal (of type const char[]). You should have got a warning and you should avoid doing that.

Upvotes: 4

Related Questions