Link to home
Start Free TrialLog in
Avatar of coollizard
coollizard

asked on

Storing a hostname in an array

Hello y'all!

I know that C does not have the ability to use strings, only arrays of characters. I want to store a web address in an array for a client to access later on, how would i go about hard coding this address?

Thanks in advance!
Avatar of AlexFM
AlexFM

You can define global variable:

char* sAddress = "https://www.experts-exchange.com";

and use it in any place in the program.


There are many things to consider...
Is your array a fixed array? If so, that means you can store just a fixed quantity of web addresses.
Maybe a linked list will be better.

If you will store a string into an array, you will need an element counter and maybe to store a copy of the string, since original string can disappear from memory. Something like this:

AddAddress(char **array, int index, char *theString)
{
        char *strCopy = malloc(strlen(theString)+1);
        strcpy(strCopy, theString);

        array[index] = strCopy;  /* store a copy of original string */
}

Notice you will need to scan all array at program end to free all strings allocated with malloc().
Good luck,
Jaime.
Note that

>char* sAddress = "https://www.experts-exchange.com";

will let the actual characters 'h' 't' 't' 'p' etc. be stored in an arbitary place in memory, usually somewhere read-only. Modifying the location where sAddress points to, might cause problems:

char* sAddress = "https://www.experts-exchange.com";
sAddress[0] = 'f'; /* Bad */
strcpy(sAddress, "http://somewhere-else"); /* Bad */

To actually create an array and copy characters inside..... Well, you create an array and copy characters inside:

char address[100]; /* Maximum length = 99, need the last char to be '\0' */
strcpy(address, "https://www.experts-exchange.com");

Or, just initialize the array with the string:

char address[100] = "https://www.experts-exchange.com"; /* Some characters will be wasted */
char address[] = "https://www.experts-exchange.com"; /* An array of just sufficient size to store the characters in the URL plus one for the terminating '\0' will be created, you will not be able to store larger URLs */
ASKER CERTIFIED SOLUTION
Avatar of madhurdixit
madhurdixit

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of coollizard

ASKER

Thats great man, thanks a lot! The malloc way is definately the more efficient way of doing things. Cheers!