Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

strncpy function with two character arrays

Status
Not open for further replies.

embeddedlover

Full Member level 5
Joined
Aug 10, 2007
Messages
277
Helped
46
Reputation
92
Reaction score
38
Trophy points
1,308
Activity points
3,155
I have the following two code snippets:

Code 1:

char *a = "India";
char *b = "and";
strncpy(a,b,3);

Code 2:

char a[10] = "India";
char b[10] = "and";
strncpy(a,b,3);

Code snippet 2 works and snippet 1 doesn't work why?
 

dude
in snippet 1 you are trying to copy the in string pointer....if you do like this the compiler will give run time error segmentation fault...once read about strings using pointers concept you will get idea....
 

in
Code:
char *a = "India";
"India" is a string constant and the variable a is a pointer to it. You can use ato read the characters but an attempt to write to it will cause a segmentation error.
in
Code:
char a[10] = "India";
a is an array length 10 initialised with the string "India", you can read or write the array elements.
 

thank you, got it.... char *a defines a character pointer, pointing to character constant "India".
where as char b[10] defines an array, which can have an string assigned within it's space.
We can copy string from one array to another but not character pointer.
the way we declared matters here...

you can use ato read the characters but an attempt to write to it will cause a segmentation error.

writing is not allowed
but assigning the following way is allowed isn't?

char *a = "India";
char *b = "and";
a = b;
 

but assigning the following way is allowed isn't?

char *a = "India";
char *b = "and";
a = b;

yes, a and b are pointers which can hold the address of any char. You have assigned a to point to the start of string constant "and", i.e. both a and b holds the address of 'a'

you cannot do the following
Code:
char a[] = "India";
char b[] = "and";
a = b;
the identifiers a and b are constant pointers to the start of the arrays and the assignment a=b is illegal
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top