PDA

View Full Version : array of strings in c



jordanmthomas
March 1st, 2007, 06:37 AM
I have a question that should be easy to answer, but I have been trying to fix it for a while now with no success. I have an assignment to read lines from a file and then sort them. Sounds simple enough, but I am having trouble.

I am making an array of pointers to characters which are all pointing to nothing:

char** array;
array = (char **)calloc(numLines, sizeof (char *));

for(i = 0; i < numLines; i++)
{
array[i] = (char*)malloc(sizeof(char*));
}

It is my understanding that I can point these empty character pointers to a string and I'd be set.
Say I have a char pointer named addMe pointing to "jordan"
I have printed this out successfully so I am certain that it what it points to.

Why is it that this does not work? :

array[0] = *addMe;
Doesn't this make the char* in array[0] point to the contents of addMe?
It seems to halfway work, but it only gets the first character from addMe; i.e.

printf("%s\n",*array[0]);
would give "j" and not "jordan"

I am sure it's something simple I am missing but I can't figure it out.

jordanmthomas
March 1st, 2007, 06:58 AM
Funny how writing your question basically gives you your own answer. :)

Now I am adding it like this:

array[i] = addMe;
and printing like this:

printf("%s",array[i]);

Thanks for any interest you might have had.

slavik
March 1st, 2007, 07:14 AM
(char *) is 4 bytes since it is a pointer to a character ...

you want something along the lines of:


char *lines[NUMLINES];
char buffer[81];
while (fgets(buffer,80,stdin) != NULL) {

buffer[strlen(buffer)] = '\0'; /* change newline char to NULL char */
lines[iterator] = (char *)malloc(strlen(buffer));
strcpy(lines[iterator],buffer);
iterator++;
}
/* sort the array */
/* print the array */
puts(lines[iterator]); /* should work fine */


note, code is untested :P

for comparison, perl code :)



#!/usr/bin/perl

while (<>) { push @_, $_; }
print sort @_;

hod139
March 1st, 2007, 02:46 PM
(char *) is 4 bytes since it is a pointer to a character ...

you want something along the lines of:
[code]
char *lines[NUMLINES];
char buffer[81];
while (fgets(buffer,80,stdin) != NULL) {
buffer[strlen(buffer)] = '\0'; /* change newline char to NULL char */
lines[iterator] = (char *)malloc(strlen(buffer));
strcpy(lines[iterator],buffer);
iterator++;}[code]
Please don't ever use strcpy (even if you are using it correctly)!! It never checks the length of the input string and is a very commonly used vector for buffer overflows. You should get into the practice of always using strncpy, followed by setting the newline = '\0'.


strncpy(lines[iterator], buffer, strlen(buffer)); // only copy strlen(buffer) bytes
lines[iterator][strlen(buffer)-1] = '\0'; // Just to be extra safe