lol I read that before, but I'm still confused!!!!!!!!!!
lol I read that before, but I'm still confused!!!!!!!!!!
When you use just the name of an array as an argument to a function, it will pass in a pointer to the 0th element of the array.arrays work like pointers
A c-style string is an array of characters, with the convention of placing a null-character after the end of the string.
If you read the link by Andreas and still confused read this :
Array indexing in C start from 0 .This is not fortran.
So if i have this declaration
then i have 5 elements.Code:char array[5];
- the first element in slot (as you say ) array[0]
- the second element in slot array[1]
- the third element in slot array[2]
- the fourth element in slot array[3]
- the fifth element in slot array[4]
this all the memory that belongs to you.If you try to access more, then you are cheating and you will receive a segmentation fault or a bus error.
In C we have to terminate our strings with null terminator.Thus we need space for the null terminator to be saved to.
Here are seven examples :
The first one is a string literal.This means that you can not modify its contents but you can set the pointer(s0) to somewhere else.It is terminated by the null terminator automatically.Code:/* 1 */ char *s0 = "Lugano"; /* 2 */ char s1[] = "Bellinzona"; /* 3 */ char s3[255] = "Locarno"; /* 4 */ char s4[] = {'M','e','n','d','r','i','s','i','o'}; /* 5 */ char s5[10] = {'G','i','u','b','i','a','s','c','o'}; /* 6 */ char s6[] = {'C','h','i','a','s','s','o','\0'}; /* 7 */ char s7[6] = "Ascona";
/* 2 */
The compiler will automatically allocate enough space for the string to fit in ,plus one more slot for the null terminator.As a result the size of array s1 will be 10+1 = 11 .Remember that you can modify the contents of this string but you can not set the s1 somewhere else.
/* 3 */
The compiler will allocate an array of size 255.In the first 7 slots (slot 0 up to slot 6 ) the contents of the string are going to be saved.In the 7th slot, which the 8th element of your array, a null terminator will be placed by the compiler.Actually because of the brackets, the rest of the unused slots are going to be set at zero.
/* 4 */
Now the compiler can not understand that you want to store a string.He only sees characters that are irrelevant for him the one from the other, thus no null terminator will be set after the last 'o'.The size of the array will be 9.This is the length of the string.No null terminator will be added.
/* 5 */
The length of the string is 9 characters.So because of the brackets, the compiler will fill the first 9 slots ( slot 0 up to slot 8 ) with the contents of the string, thus the letters , and will put a null terminator after it, because the 9th slot is still unused, so there is space for the nul terminator.This happens because the size of array s5 is equal to 10.If we hadn't specify the size of the array s5 by ourselves, then we would have pretty much the same situation as in case 4.
/* 6 */
A well defined string.The size of the array will be equal to 8.Slots 0 up to slot 6 will contain the letters and the 7th slot the null terminator.Notice that nothing is done automatically here, we set the null terminator ourselves.
/* 7 */
String "Ascona" has length equal to 6.We have specified the size of array s7 to six.So the letters will be stored successfully, but there is no space for the compiler to go and put the null terminator for us.So , no we will not lose data by getting the last letter replaced by the null terminator.No null terminator will be placed after the string, because there is no space for it.
But why is everybody so mad about terminating their strings with the null terminator?
An easy answer is because the functions from the standard libraries of C assume that every single string is terminated properly , which means that after the contents of the string there is a null terminator. Always you should respect this convention.
Well maybe this example was too much for a beginner.If you did not understand everything, do not worry , practice a little more and come to read the example.
Take bye bye message :
- Array indexing starts from zero.
- Always terminate your strings with the null terminator
Hope this helps
Not sure if this is glibc specific or not, but it seems to work for reading in an entire line from current position without the trailing new lineCode:char buffer[200]; /* safer length for your buffer */ printf("Enter your first and last name: "); scanf("%[^\n]",buffer); /* this will read an entire line including spaces between words */
Last edited by twiki; 11-17-2012 at 05:34 PM. Reason: Corrected the code listing with code tags
No it is certainly not true. There is no "slot 3". Any attempt to use "slot 3" (access its value, write to it) causes undefined behaviour. Anything can occur as a result of undefined behaviour, whether it is behaviour that makes sense to you or not. Not crashing is one allowed possibility. Crashing is another allowed possibility. Initiating a current surge through a USB port in order to electrocute the programmer is also an allowed possibility (unfortunately an unlikely possibility, as a system which did that would increase average competence of living C programmers immensely).
Wrong.
In C, by convention, a string is an array of char with the end marked by a character with value zero.
Defining an array of char ("char f[3];") does not create a string. It creates an array of exactly three characters (which may or may not be initialised, depending on where the definition occurs). It does not create an array of four characters, and certainly does not initialise such a fourth character with value zero.
Last edited by grumpy; 11-17-2012 at 05:49 PM.
Thank you aaaalllll... really helped me out here
STD, the examples were just great!
Last edited by Ashl7; 11-18-2012 at 02:15 AM.
use string functions gets(astring) and puts(astring) to read and write strings including spaces
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I had some question not related to programming this time
Is it necessary to take C++ before taking Java?! is it going to be hard to understand Java if I don't learn C++ in advance?! which one is harder?! how similar they are?! is learning C++ even needed if I learn Java language?!
if someone can answer these questions, I just thought not making a new thread because of it and ask all my questions here
Hey all
can anyone explain to me why this program output is AB?
I mean I think it should be ABC?! shouldn't it?!
Code:#include <stdio.h> int main() { char *ch; char vch[]={'A','B','\0','C','\0'}; ch= vch; printf("%s",ch); return 0; }
Last edited by Ashl7; 12-15-2012 at 01:51 PM.
and why does this one prints out AB?! it should be A itself, since the character in slot 0 is A!!!
Code:#include <stdio.h> int main() { char *ch; char vch[]={'A','B','\0','C','\0'}; ch= &vch[0]; printf("%s",ch); return 0; }
Think of a pointer as an arrow which points to somewhere in memory. In this case the spot in memory called vch is 5 characters
'A' 'B' '\0' 'C' '\0'
The expression vch[0] refers to the single character in slot 0, represented as 'A'.
The expression &vch[0] constructs a pointer to this character, which might be represented by drawing an arrow to the character in a diagram:
->'A' 'B' '\0' 'C' '\0'
Printing a string is defined very simply: print the character that the arrow points to, advance the arrow, print that character, advance the arrow, and so on. Keep doing this until the arrow points to a '\0' character.
This is the answer to both of your previous questions. Now you should be able to answer the output of:
Code:vch[2]='x'; printf("%s", &vch[1]);
printf takes a pointer and prints out every character on from there until it encounters a nul character.
You are giving it a pointer to the same string in both cases where the the third character it sees is a nul. So of course they behave the same.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
This is a string - but the last char you will never see:
Four score and seven years ago\0
This is just a bunch of chars - but NOT a string:
Four score and seven years ago
Without the NULL char on the end, there is no string, in C.
This is a way to use scanf() to bring in first and last names, with just a space between them, on the same line of text. Each struct member is separated by a comma.
There is a field length format specifier for scanf(), but it's for strictly formatted data only. It simply cuts off any further data entry - BOOM!Code:/* The names.txt file is: Abe Alfa,10,Male Bella Bravo,15,Female Charles Charlie,18,Male Donna Delta,22,Female */ /* #include <stdio.h> typedef struct { //declare a structure char fname[30]; //for each student record char lname[30]; int age; char sex[6]; }students; int main(void) { FILE *fpIn; int i,studnumber; char buffer[80]; students stud[4]; //make an array of student records fpIn=fopen("names.txt","r"); if(!fpIn) { printf("Error opening file!\n"); return 1; } i=0; while(fgets(buffer, sizeof(buffer), fpIn)) { sscanf(buffer, "%s %[^,],%d,%s",stud[i].fname,stud[i].lname,&stud[i].age,stud[i].sex); printf("Name: %s %s \nAge: %d \nSex: %s\n",stud[i].fname,stud[i].lname,stud[i].age,stud[i].sex); ++i; } studnumber=i; fclose(fpIn); printf("\nnumber of students: %d \n",studnumber); return 0; }
Probably that's not what you want.