Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A trivial question?

Status
Not open for further replies.

Protonman

Programmer
Apr 1, 2005
6
CH
Hi,

I'm asking this question out of curiosity rather than neccessity:

E.g:

------
//Vars

char foo[20] = "abcd";
char *bar = "ghjk";


a) scanf("%s",bar); /*doesn't work; compiles but crashes (using g++) */

b) strcat("qwerty",foo); /* ditto, although foo shouldn't change */

c) strcat(bar,foo); /*" "; " " "*/
strcpy(...); /* ... */

d) strcat(foo,bar); /*works, no problem*/
strcpy(...); /* ... */

-----

The same "problem" arises when using other string functions such as strcpy etc. Also, why can't you "scanf" into a char *, only into a char * constant (array name)?

Is this because "bar" is a pointer and "foo" a constant pointer?

I'm just very curious to know why and can't seem to figure it out.

Many thanks in advance

Protonman
 
All your char * point to string constants, which implementations are free to make read-only.
This means that if you try, you get a segmentation fault as the OS steps in and kills your program.

If you point at memory you can modify, say an array, then all is well.
Code:
  char foo[20] = "abcd";
  char *bar = foo;
You can scanf into bar, and it will just write over whatever foo is initialised to.

--
 
The solution to ""modify"" the content of * is to allocate memory for it. (functions malloc, calloc, realloc). Personaly I prefer this solution because you don't have to declare size of the array before compilation and can increase it dynamically.
Code:
char *bar;
char *tmpbar;
bar=malloc(10/*any number*/*sizeof(char));/*equal to bar[10]*/
bar[0]='c';/*now it's legal*/
tmpbar=realloc(bar,(10+10)*sizeof(char));/*if you wan't bigger size*/
/*tmpbar is used because when you run out of memory realloc returns NULL and all data is lost (memory leak)*/
if(tmpbar)
bar=tmpbar;
free(bar); /*dispose the pointer at the end*/

Martin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top