1

Let's say I have a char pointer called string1 that points to the first character in the word "hahahaha". I want to create a char[] that contains the same string that string1 points to.

How come this does not work?

char string2[] = string1;
1
  • There's an assumption implicit in the question that arrays and pointers are the same thing in C (trying to initialize a new array of char by reference to a char* pointer). This is not the case and it's important to understand the differences to avoid introducing subtle bugs into your program. Commented Aug 24, 2013 at 1:24

3 Answers 3

3

"How come this does not work?"

Because that's not how the C language was defined.

You can create a copy using strdup() [Note that strdup() is not ANSI C]

Refs:

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

Comments

0

1) pointer string2 == pointer string1

change in value of either will change the other

From poster poida

char string1[] = "hahahahaha";
char* string2 = string1;

2) Make a Copy

char string1[] = "hahahahaha";
char string2[11]; /* allocate sufficient memory plus null character */
strcpy(string2, string1);

change in value of one of them will not change the other

Comments

0

What you write like this:

char str[] =  "hello";

... actually becomes this:

char str[] =  {'h', 'e', 'l', 'l', 'o'};

Here we are implicitly invoking something called the initializer.
Initializer is responsible for making the character array, in the above scenario.
Initializer does this, behind the scene:

char str[5];

str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';

C is a very low level language. Your statement:

char str[] = another_str;

doesn't make sense to C. It is not possible to assign an entire array, to another in C. You have to copy letter by letter, either manually or using the strcpy() function. In the above statement, the initializer does not know the length of the another_str array variable. If you hard code the string instead of putting another_str, then it will work.

Some other languages might allow to do such things... but you can't expect a manual car to switch gears automatically. You are in charge of it.

1 Comment

It ACTUALLY becomes char str[] = {'h', 'e', 'l', 'l', 'o', '\0'}; Every string literal has an implicit '\0' attached to the end of it.

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.