-3

My code looks like this:

char source[] = "the wrong son";
char output[80];
int  i, j = 0;

for ( i = 0; source[i]; i++ )
    if ( i < 4 || i >= 10 )
        output[j++] = source[i];

output[j] = '\0';

Why can't I replace a string with other string like this:

source = output;

Instead of doing it a longer way:

for ( i = 0; output[i]; i++)
    source[i] = output[i];

source[i] = '\0';

When I tried doing source = output;, nothing happens. How come?

7
  • but how you defined strings? Jul 2, 2014 at 5:26
  • you can use C++ and std::string behave as you expected
    – Bryan Chen
    Jul 2, 2014 at 5:32
  • 1
    In C string is not considered as primitive data type.
    – kvivek
    Jul 2, 2014 at 5:33
  • Instead of doing it a longer way. why go for it? have you not know strcpy? Jul 2, 2014 at 5:38
  • It was an assignment of creating a removeString function (to remove a part of a string), and the book did not cover strcpy yet. I was just wondering why source = output didn't do anything.
    – vxs8122
    Jul 2, 2014 at 5:40

2 Answers 2

1

In C string is not considered as primitive data type.hence,your statement won't fit!

Had,strings been independent and primitive data-types,you would have easily done it.But,this is restricted and against the C language specifications.

You'll have to go through the first way! Alternatively,you can also go for strcpy() method.

0

From the C Standard ISO/IEC 9899:201x:

An lvalue is an expression (with an object type other than void) that potentially designates an object; 64) if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const- qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const- qualified type.

An array is an unmodifiable lvalue object.

3
  • 1
    Well that's bullschildt by K&R really. Of course an array name is a variable, namely an array type variable. It is just a variable that can't use it as a lvalue in an assignment, because the C language says so.
    – Lundin
    Jul 2, 2014 at 6:36
  • 1
    Bear in mind that K&R was written long before C standardization. When C89 came out, K&R2 was released which had the code partially fixed up but a lot of the text remained unchanged
    – M.M
    Jul 2, 2014 at 8:39
  • What did K&R mean by "arrays are not variables"?
    – 0KL
    Jul 2, 2014 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.