Answer the question
In order to leave comments, you need to log in
About the nuances of working with strings and arrays in C
I have a question that I can't find a definitive answer to.
In C language, you can copy lines:
void strcpy(char *s, char *t)
{
while (*s++ = *t++)
;
}
int ar[] = {0,1,2};
// Мне ничего не мешает сослаться на элемент за приделом массива
ar[5] = 5;
// и в таком случае
printf("%d\n", ar[5]);
// Выведет значение - 5
Answer the question
In order to leave comments, you need to log in
C is a statically typed language. This means that during the declaration of a variable, a memory area is allocated for it, which does not change later. Accordingly, if there is an exit outside this area, then there are chances to corrupt neighboring data, program code, or get a system exception when trying to write outside the memory allocated to the program.
The function of copying strings is in the standard string.h library and is somewhat more complicated. Try using your function to execute the following code:
char str[20] = "Прпущен символ";
strcpy(str+3, str+2);
str[2] = 'о';
printf("%s\n", str);
No one allocates memory for you in C.
Quote from here :
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
Your question has already been answered - you and only you monitor the sufficiency of the memory block. Strings in C are almost indistinguishable from a regular array. Unless the compiler puts a zero character automatically if the string is initialized in quotes.
Example 1: An
array of 20 char elements is allocated, the first 6 of which will be filled with values, the remaining 14 will have random values.
Example 2: An
array of 20 char elements is allocated, the first 5 of which will be filled with values, the remaining 15 will have random values.
I also wanted to draw your attention to one point.
pointer to char from where you copy the string should be declared constant. In C++, this has been necessary for a long time. In C too. Though, I do not know from what version of the standard.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question