#strings in C
1 messages · Page 1 of 1 (latest)
<@&987246683568103514> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
also the last 2 letters are garbage values? since they are random every time i run the program
'u' and 'j' here
u have undefined behavior here
ur strings are incorrect
in c, arrays dont know their length
so how does strlen work? how does it know where the text ends?
it goes until it finds the magic value \0
the null-terminator
in ur program, it seems it found one 2 spots after the string
so it printed up to there
but it could be anywhere or nowhere. its undefined behavior and pure coincidence that there was a \0 in memory there
sooo... how to do it proper? ur array has to have 6 spots, not 5. and the last char should be '\0'
then it works
Shouldn't a string literal automatically add the \0 ?
it does but length is 5 of the array..
better way is char str[] = "apple", let compiler do it
#include <stdio.h>
#include <string.h>
int main(){
char str1[6] = "apple";
printf("%s \n",str1);
printf("Length of the sting is %d \n",strlen(str1));
for(int i = 0; str1[i] != 0; i++)
printf("%c \n",str1[i]);
return 0;
}
Detected code, here are some useful tools:
#include<stdio.h> #include<string.h> int main() {
char str1[6] = "apple";
printf("%s \n", str1);
printf("Length of the sting is %d \n", strlen(str1));
for (int i = 0; str1[i] != 0; i++) printf("%c \n", str1[i] );
return 0;
}
yes but what if i want an array of characters and not a string?
oh i guess then i cant use the strlen
exactly
any of the string methods will assume the end is marked by the null terminator
how is that possible
some of the methods also have an overload where u can explicitly tell it the length manually, so that it can also work with strings without null terminator
oh its weird behaviour cuz strlen() was expecting a string?
it just read the memory beyond ur array and by coincident, there was a 0 byte there, 2 spots later
pure coincident
remember that c has no safety features here. it just reads the memory beyond ur array
i ran it again
how is it still 7?
i ran it a few times its always 7?
maybe the "0" byte is still at that memory location until i over write it?