Reputation: 29
So I'm enrolled in a beginner level systems course at my university and my professor mentioned that array sizes cannot be changed because they are set in memory.
Furthermore, that strings in C are just arrays of characters.
So my question is, how can strings of different lengths be copied using strcpy, when the lengths themselves cannot be changed?
(Currently 2:30am and have an exam in 1 day)
Apologies it's a beginner question but any help is very much appreciated!! Thanks :)
Upvotes: 0
Views: 1129
Reputation: 30926
The simple answer is, the facts don't change even if we copy string using strcpy
. Once declared the size of an array won't change. In fact suppose you have a char array
char arr[]="helloworld"; //size of the array will be 11
strcpy(arr,"funny");
What is the size of the array? It's same as when declared. 11
. It didn't change from the original one.
What is the length of the string? It's 5
now.
String are null terminated char arrays. That means the array may have 100
elements but the string will be some characters null terminated and it can be anything for example 2
length or 5
length or anything that is possible given that we have space left for storing \0
.
Copying a string doesn't mean the array size changes.
Also note one thing very carefully - strings are not just array of characters, it's the NUL terminator at the end of those characters which makes it a string.
char s[4]="hell";
This is legal C code and this is not string. There is no space for \0
. You can't use it with standard string library functions. The thing is this will not work with functions like strcpy
,strlen
etc. Because those implementation depends upon the array of characters to be NUL terminated to work properly.
Beware with the last example shown in mind - writing this is Undefined behavior.
char s[4]="hell";
size_t len = strlen(s);
No you can't do that. strlen
expects something and you didn't give it one. So the right way to say things would be- (Here is a nice descriptive quote, I don't recall the source)
In c, a string is not an intrinsic type. A C-string is the convention to have a one-dimensional array of characters which is terminated by a null-character, by a
'\0'
.
1) Don't remember the source of the quote: If anybody does let me know. I kept it in a file.(Not primary source)
Upvotes: 5