Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

string question

Status
Not open for further replies.

electroRF

Member
Hi,
I have a question please.

When one performs
PHP:
char *s1 = "abcd";
or
PHP:
char *s2;

s2 = "123456";

a const (i.e. read-only) memory is created in the data segment - (i.e. not the heap/stack? is it created already in compilation?) - 5 bytes for "abcd" and 7 bytes for "123456" ?

so one cannot write new characters into s1 or s2, right? as they point on "read-only" memory?


what about:
PHP:
strcpy(s3, "hello");

also here a 'read-only' memory is created in the data segment?


Thank you very much.
 
Are you still in C.... The initialization in the first two examples is not allowed in C...

The third is correct but you will have a string "Hello" in code space ( ROM ) and a copy in data space RAM.. The string S3 can be modified..

To create a const rom string you need to do this
C:
char string[] = {"Hello!"}
 
Last edited:
Hi Ian,
Thank you very much. :)

yes, i'm writing in C.

Following your comment, perhaps my compiler approved it as its a c++ compiler, i'm installing now Visual Studio Express to use C compiler.

The third is correct but you will have a string "Hello" in code space ( ROM ) and a copy in data space RAM.. The string S3 can be modified..

So I could actually have s3 pointing on the address in the Code Space in order to save space in the data memory?

Would it be legal?
 
Yes!

In C18 or XC8 on the pic... you just create a pointer to point at the relevant text..

C:
const char text[] = {"Hello world!};
const char* romptr = &text[0];

// as opposed to

char text[] = {"Hello world!};
char* ramptr = &text[0];

Some compilers create the second array as a constant as the text is already a constant... So you would declare it volatile so it will create it in RAM..
 
Last edited:
Thank you Ian!

If I got it correctly, then the following code would have s pointing on an address in the code space, where the compiler created "help"?
C:
char* mystrcpy(char* dest, char* source)
{
    dest = source;
    return dest;
}


void main(void)
{
    char *s = NULL;

    s = mystrcpy(s, "help");

}
 
Status
Not open for further replies.

New Articles From Microcontroller Tips

Back
Top