to continue about string, pls look to this:
Code:
01#include <stdio.h>
02#include <string.h>
03
04#define STR_SIZE 70
05
06struct reckey
07{
08 char *name;
09};
11typedef struct reckey key;
12
13int main()
14{
15 char *S,*D,*T,*P,*K,A[STR_SIZE];
16 key *user;
17
18 S = "123456789 223456789 323456789 423456789 523456789 623456789\n";
19 //if we insert string to S with over than 32 karakter it will make strcpy(P,S) causing segment fault.
20
21 user = (key *)malloc(sizeof(key));
22 user->name = (char *)malloc(sizeof(char)*STR_SIZE);
23 strcpy(user->name,S);
24
25 D = S;
26 printf("%s",D);
27
28 strcpy(A,S);
29 printf("%s",A);
30
31 T = A;
32 printf("%s",T);
33
34 P = (char *)malloc(sizeof(char));
35 strcpy(P,A);
36 printf("%s",P);
37
38 K = &A[0]; //equal with K = A;
39 printf("K=%s A=%s",K,A);
40
41 printf("user->name %s",user->name);
}
i compiled with: "gcc string.c"
run : "./a.out"
output:
123456789 223456789 323456789 423456789 523456789 623456789
123456789 223456789 323456789 423456789 523456789 623456789
123456789 223456789 323456789 423456789 523456789 623456789
123456789 223456789 323456789 423456789 523456789 623456789
K=123456789 223456789 323456789 423456789 523456789 623456789
A=123456789 223456789 323456789 423456789 523456789 623456789
user->name 123456789 223456789 323456789 423456789 523456789 623456789
why syntax strcpy() can do its job when i didnt type "#include <string.h>" in line-02?
in line-22 and line-34, if i didnt include multiply STR_SIZE, the result is ok, anyone know why? or when P = (char *)malloc(sizeof(char)) how many karakter that it preserved exactly?
For this P = (char *)malloc(sizeof(char)*10) its explanation by Dark_Helmet that i've read is very clear.thx.
my conclusions:
if we want using strcpy then the syntax is: strcpy(array,string)
examples:
Code:
char *String1, *String2, Array[STR_SIZE];
key *user;
//to fill words/sentence from string_variable to other string_variable:
String1 = String2; Ok
strcpy(Array1,String1); Ok
String1 = Array1; Ok
String1 = Array1[0]; Ok
String1 = (char *)malloc(sizeof(char));
strcpy(String1,String2); Ok
user = (key *)malloc(sizeof(key));
user->name = S; Not Ok! even the result is Ok but in LIFO will cause a problem. (see in threads "what happen to my LIFO" and the explanation by Dark_Helmet)
user = (key *)malloc(sizeof(key));
user->name = (char *)malloc(sizeof(char)*STR_SIZE);
strcpy(user->name,S); Ok
if anyone has opinion to my conclusions, please tell me, i need the truth understanding. i'm very grateful.