On 8 Dec 2006 09:24:34 -0800, "santosh" <santosh.k83@gmail.comwrote:
Quote:
>OziRus wrote:
Quote:
>Hi,
>>
>I've char* array that I defined like char *str[150]. I want to read
>from a file, that contains names in each row, and assign them to my str
>char * array.
><snip>
>
>#include <stdio.h>
>#include <stdlib.h>
>
>#define MAX_NAMES 150
>#define MAX_NAME_LENGTH 256
>
>int main(int argc, char **argv) {
FILE *f;
char *names[MAX_NAMES];
int cnt;
>
/* open file */
if(argc < 2) {
fprintf(stderr, "No file specified.\n");
exit(EXIT_FAILURE);
}
else {
f = fopen(argv[1], "r");
if(f == NULL) {
fprintf(stderr, "Unable to open file: %s\n", argv[1]);
exit(EXIT_FAILURE);
}
}
>
/* allocate memory for names */
for(cnt = 0; cnt < MAX_NAMES; cnt++) {
if((names[cnt] = malloc(MAX_NAME_LENGTH * sizeof *names)) == NULL)
Why use malloc()? The size of names[cnt] is certainly not unknown or
even "dynamic". Both MAX_NAME_LENGTH and sizeof *names are
compile-time constants.
Why not just declare an appropriate array with either automatic or
static storage duration? If you did that, it:
1. Would free you from having to free().
2. Would result in a smaller memory footprint (less code).
3. Might make the difference between running or not on a non-hosted
environment. Resources can get pretty constrained on, for example,
some embedded systems. Such implementations might not even
*practically* support malloc().
4. Might unnecessarily violate coding standards (thou shall not use
dynamic memory) that are applicable to, for example, safety-critical
systems.
--
jay
Quote:
>{
fprintf(stderr, "No memory.\n");
exit(EXIT_FAILURE);
}
}
>
/* read lines into memory */
for(cnt = 0; cnt < MAX_NAMES; cnt++) {
if(fgets(names[cnt], MAX_NAME_LENGTH, f) == NULL && ferror(f)) {
fprintf(stderr, "Error reading file: %s\n", argv[1]);
for(cnt = 0; cnt < MAX_NAMES; cnt++) free(names[cnt]);
exit(EXIT_FAILURE);
}
}
>
/* print what we've read in from file */
for(cnt = 0; cnt < MAX_NAMES; cnt++)
fprintf(stdout, "%s", names[cnt]);
fflush(stdout);
>
for(cnt = 0; cnt < MAX_NAMES; cnt++) free(names[cnt]);
return EXIT_SUCCESS;
>}