Karel Adams
Karel Adams

Reputation: 305

Print only the rightmost part of a string

I am applying printf and/or other functions to a certain string of characters, read from a file. I want to skip the first 5 characters under certain conditions. Now I thought to be clever by, if the conditions apply, increasing the string pointer by 5:

 if (strlen(nav_code) == 10 ) {nav_code = 5+nav_code;}

but the compiler refuses this:

error: assignment to expression with array type

What have I misunderstood? How to make my idea work - or is it a bad idea anyway?

Upvotes: 2

Views: 217

Answers (3)

tdao
tdao

Reputation: 17668

I am applying printf and/or other functions to a certain string of characters, read from a file. I want to skip the first 5 characters under certain conditions.

If printf is all what you need, then sure you can skip the first 5 characters.

Given nav_code is string (either char array or char pointer), then:

printf( "%s", nav_code + 5 );  // skip the first 5 characters

Of course you need to make sure your string has more than 5 characters, otherwise it's flat out illegal as out-of-bound access.

Upvotes: 1

Stephan Lechner
Stephan Lechner

Reputation: 35154

It's probably becuase nav_code is not a pointer but a character array like char nav_code[50]. Try the following:

char nav_code[50];
char *nav_code_ptr = nav_code;
if (strlen(nav_code_ptr) == 10 ) {nav_code_ptr += 5;}
// forth on, use nav_code_ptr instead of nav_code

Upvotes: 6

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

In your code, nav_code is an array and arrays cannot be assigned.

Instead, use a pointer, initialize that with the address of the first element of the array, make pointer arithmetic on that pointer and store the updated result back to the pointer.

Upvotes: 0

Related Questions