|
|
View previous topic :: View next topic |
Author |
Message |
JULIEN LAFFITTE
Joined: 28 Mar 2007 Posts: 20
|
string as parameter |
Posted: Thu Jul 19, 2007 2:50 am |
|
|
hello i want to know :
-if it's possible to give a string as parameter like in the example
-if yes what the correct syntax
-if after executing bidule(), machin1[] or machin2[] are modified
Code: | char machin1[4],machin2[4];
void bidule(char machin[])
{
...
machin[i]="e";
...
machin[y]="t"
}
void main (void)
{
...
bidule(machin1[]);
bidule(machin2[]);
...
} |
thanks by advance |
|
|
Ttelmah Guest
|
|
Posted: Thu Jul 19, 2007 3:49 am |
|
|
First critical thing. Nothing you show here is a 'string'!...
A string, is simply an array of bytes, _terminated by a 0_. Now, you declare a byte array, and write a couple of characters to it (wrong declarations used here, a single character, is 'e', not "e"). But you do not terminate the array, so it is not a 'string'. It is also critical to remember that a 4 character 'string', must be 5 bytes long, to allow for the terminator. In C, arrays and pointers are interchangeable, so the normal way to deal with handing 'strings' to functions, is to pass the pointer to the array.
So:
Code: |
char str1[5], str2[5];
void demo(char * strptr) {
strptr[0] = 'x';
strptr[1] = 'y';
strptr[2] = 'z';
strptr[3] = '.';
//Now to be a _string_, this must be terminated
strptr[4] ='\0';
}
void main(void) {
//For an array, the name of the array, is the address of the
//first element. This is done so you can just use the 'name'
//in function calls etc., to pass the address.
demo(str1);
demo(str2);
printf("%s %s\n\r",str1,str2); //will print 'xyz. xyz.' from the strings
//Now to copy a whole _string_, you use strcpy. So:
strcpy(str1,"test");
printf("%s\n\r",str1); //will print 'test' from the first string.
//Now the caveat.
strcpy(str1,"test2"); //This will _destroy_ whatever is in memory
//immediately after 'str1', since it is trying to write six characters
//to a memory are declared to hold five...
while (TRUE) ;
}
|
Best Wishes |
|
|
JULIEN LAFFITTE
Joined: 28 Mar 2007 Posts: 20
|
|
Posted: Thu Jul 19, 2007 6:00 am |
|
|
Thanks a lot for these precisions
best regards |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|