[Dev-C++] Pointer string declaration initialization problem (?)
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <and...@su...> - 2005-05-21 15:47:50
|
Dear users,
This is a simple question:
Please, consider the following the two codes with
their respective results:
code 1:
1 -#include <stdio.h>
2 -#include <stdlib.h>
3 -#include <string.h>
4 -
5 -int main()
6 -{
7 - char *name="name1";
8 -
9 - printf("%s\n", name);
10- strcpy(name, "name2");
11- printf("%s\n", name);
12-
13- system("PAUSE");
14- return 0;
15-}
execution results from code 1:
Access violation as a consequence of line 10.
code 2:
1 -#include <stdio.h>
2 -#include <stdlib.h>
3 -#include <string.h>
4 -
5 -int main()
6 -{
7 - char *name;
8 -
10- name = malloc(6*sizeof(char));
11- if(!name) exit(1);
12- strcpy(name, "name1");
13- printf("%s\n", name);
14- strcpy(name, "name2");
15- printf("%s\n", name);
16-
17- system("PAUSE");
18- return 0;
19-}
execution results from code 2:
name1
name2
My question:
Doesn´t a pointer support an implicit memory allocation
through the declaration/inicialization on line 7 from code 1
the same way a
char name[]="name1";
can do?
Regards
Andre
--
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.322 / Virus Database: 266.11.14 - Release Date: 20/5/2005
|