|
From: Luigi S. <gi...@li...> - 2001-07-17 18:09:17
|
In a C program you can ask for memory in a "static fashion" (i.e. at compile time) and in a "dynamic fashion" (i.e. at execution time). When you define "linha1" by the line: char linha1[31]; /* 1 is for the terminating '\0' */ you are using static memory, this means that linha1 will be made of 30 chars during the whole execution, and its size is known at compile time. If you wish to use dynamic memory, then I suggest you use calloc instead of malloc (calloc is for arrays) char *linha1; ... linha1 = (char *)calloc(31, sizeof(char)); /* 1 is for the terminating '\0' */ When you no longer need the dynamically allocated variable linha1, you should release the memory by the following: free(linha1); Dynamic memory is used when the size of the string is not known in advance, since in your code, you already know that no string has more than 30 chars, you should use static memory. In my opinion your code should be: --- #define MAX_SIZE 31 char linha1[MAX_SIZE]; ... fgets(linha1, MAX_SIZE, script); ... --- At 12.51 17/07/01 -0300, you wrote: >I can't find any tutorial about Malloc for strings. >I want to read a string (line) from a file named 'script'. Each line has >one string with diferent size. >The MAX string will have 30 chars. >I know it is very simple, but I can't find the solution. > Thanks, > Iuri >--------- > char linha1 [30]; > char *linha1_ptr = linha1; > linha1_ptr = malloc (30); >... > fgets (linha1_ptr , sizeof(linha1_ptr) , script); > printf(linha1_ptr,"\n"); > fputs(linha1_ptr, tudo); > write(sockfd, linha1_ptr, sizeof(linha1_ptr)); > write(sockfd, "\n\r",2); >------------ --- gisan |