By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,720 Members | 2,244 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,720 IT Pros & Developers. It's quick & easy.

How do I convert this string array to an array of dynamic strings in C

P: 1
I need to read a txt and store it in a dynamic string array
the code I have now does but memory is wasted because it is static

I like to read a txt and every word stored in a string array of dynamic


Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.      #include <conio.h>
  3. #define MAX_CHARS 20
  4.  
  5. typedef char string[MAX_CHARS+1];  // leave one space for '\0'
  6.  
  7. main(){
  8.    int i;
  9.    string array[4];
  10.  
  11.    FILE *data;
  12.    data = fopen("ard.txt","r");
  13.    for(i = 0; i < 4; i++)
  14.         { fscanf(data, "%s", array[i]); } // no need for & with %s
  15.            printf("%s",array[3]);
  16.    getch();
  17. }
  18.  
  19.  
Aug 31 '16 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
Your static array is:

Expand|Select|Wrap|Line Numbers
  1. string array[4];
My first question is: How do you know memory is wasted? I mean, how long are the strings in the elements of this array. If you had 4 strings of 2000 chars each or if you had 4 strings of 10 chars each, your array would be coded the same way.

You would have to look at the implementation of the string template to see if memory is wasted. These are C++ string objects and not some char array in C with a \0 terminator.
Sep 1 '16 #2

Post your reply

Sign in to post your reply or Sign up for a free account.