Computing.Net > Forums > Programming > an array of strings in C

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

an array of strings in C

Reply to Message Icon

Name: geo
Date: July 20, 2003 at 13:19:06 Pacific
OS: xp pro
CPU/Ram: p3
Comment:

How do you allocate more memory for a pointer in straight C? in C++ it would look like this:


char *string;
string = new char[11];
string = "hello world";

What I need to do is create and array of strings to hold file names. I have mostly C++ experience. I don't think the 'new' keyword is allowed in C.




Sponsored Link
Ads by Google

Response Number 1
Name: Don Arnett
Date: July 20, 2003 at 13:44:33 Pacific
Reply:

You use malloc and calloc. Besides taking different parameters, the main difference is that calloc clears out the allocated memory by filling it with zeros.

The program below allocates an array of 5 character pointers and then assigns strings to the pointers. Many times you'll use calloc/malloc to allocate the individual strings also.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  char **myFilenames;
  int filenameCount = 5;

  myFilenames = (char**)calloc(sizeof(char**),filenameCount);
  if (myFilenames == NULL) {
    printf("Error allocating filename array\n");
    exit(1);
  }

  myFilenames[0] = "filename1.txt";
  myFilenames[1] = "filename2.txt";
  myFilenames[2] = "filename3.txt";
  myFilenames[3] = "filename4.txt";
  myFilenames[4] = "filename5.txt";

  printf("0 = %s\n",myFilenames[0]);
  printf("1 = %s\n",myFilenames[1]);
  printf("2 = %s\n",myFilenames[2]);
  printf("3 = %s\n",myFilenames[3]);
  printf("4 = %s\n",myFilenames[4]);

  free(myFilenames);

}


0

Response Number 2
Name: geo
Date: July 20, 2003 at 14:30:31 Pacific
Reply:

Thanks I will try that.


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: an array of strings in C

sorting an array of string in java www.computing.net/answers/programming/sorting-an-array-of-string-in-java/18011.html

C arrays of strings from a file www.computing.net/answers/programming/c-arrays-of-strings-from-a-file/14025.html

C++ Arrays (Simple Q) www.computing.net/answers/programming/c-arrays-simple-q/4274.html