473,382 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

How to copy char * to char *array?

15
Hi all,
I've been working on this code since morning and seems like I need stronger skills on pointers n arrays.
I'm trying to read the content of a config file, which has x lines and then pass it to an array of characters.

Not really sure if I did use the strtok function correctly, but here's what I got so far..

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include <string.h>
  5. #include <mysql.h>
  6. #define MAXLENGTH 1024
  7. char *extarray[20];
  8. char temp[50];
  9. int add2array(char*,int);
  10.  
  11. int add2array(char *a, int b)
  12. {
  13.     printf("add2array...\n");
  14.     sprintf(temp,a);
  15.     extarray[b] = temp;
  16.     return 0;
  17. }
  18. int main( int argc, char *argv[] )
  19.  
  20. {
  21.  
  22.     char *v_file  = "/home/abuser/configpolicy.txt";
  23.  
  24.     char *token;
  25.     char line[256];
  26.     int linenum = 0;
  27.     FILE * _file; 
  28.  
  29.     int a;
  30.  
  31.     // THIS PART GETS THE DETAILS FROM config file 
  32.  
  33.     _file = fopen(v_file, "r");
  34.     if(_file == NULL) 
  35.         return -1;    
  36.  
  37.     while(fgets(line, 256, _file) != NULL)
  38.     {
  39.         char ext[256];
  40.         if(sscanf(line,"%s", ext) != 1)
  41.         {
  42.             fprintf(stderr, "syntax err-line %d\n", linenum);
  43.             continue;
  44.         }
  45.  
  46.         token = strtok(ext,";");
  47.         a=0;
  48.         while(token!=NULL)
  49.         {
  50.             //getDirHash(token);
  51.             //extarray[linenum]=token;
  52.             if(a == 0)
  53.                 add2array(token,linenum);
  54.             token = strtok(NULL,";");
  55.             a++;
  56.         }
  57.         linenum++;
  58.     }
  59.     // END
  60.     for(a=0;a<4;a++)
  61.         printf("array %d is %s\n", a,extarray[a]);
  62.     return 0;
  63.  
  64. }
  65.  
This is the config file's content:
Expand|Select|Wrap|Line Numbers
  1. .txt;new;delete
  2.  
  3. .txt;tamper;restore
  4.  
  5. .exe;new;delete
  6.  
  7. .exe;tamper;restore
  8.  
This is the output of the code:
Expand|Select|Wrap|Line Numbers
  1. add2array...
  2. .txt
  3. add2array...
  4. .txt
  5. add2array...
  6. .exe
  7. add2array...
  8. .exe
  9. array 0 is .exe
  10. array 1 is .exe
  11. array 2 is .exe
  12. array 3 is .exe
  13.  
Jan 6 '11 #1
5 7570
Banfa
9,065 Expert Mod 8TB
strtok returns pointers into the buffer supplied to it at line 46 of your code.

You store the first pointer returned by strtok in an array. This sequence is repeat several times, once for each line in your file.

However you only have one buffer defined on line 256, if you printed the pointer values of your array extarray rather than what is pointed to you would find they are all the same and you would find that there are in fact the address of extarray.

Not only that but at line 60 where you do the printing extarray has gone out of scope and no longer exists as a variable so you have invoked undefined behaviour by accessing data outside an allocated variable.

For what you are trying to do you can not store pointers.
Jan 6 '11 #2
horace1
1,510 Expert 1GB
following on from comment by banfa you could do something like
Expand|Select|Wrap|Line Numbers
  1. char extarray[20][80];
  2.  
  3. int add2array(char *a, int b)
  4. {
  5.     printf("add2array...\n");
  6.     sprintf(temp,a);
  7.     strcpy(extarray[b],temp);
  8.     return 0;
  9. }
  10.  
Jan 6 '11 #3
donbock
2,426 Expert 2GB
Line 14 of your program uses sprintf to copy string a into buffer temp. Bad things will happen if string a happens to contain a percent character. It would be better to use strcpy. It would be best to use strncpy. Don't forget to explicitly append the null terminator character if you use strncpy.

As mentioned earlier, you achieve little by having an array of char-pointers that all point to the same buffer. Instead, you want add2array to malloc a new buffer (be certain it is big enough), copy the input string into the new buffer, and load the address of that buffer into the char-pointer array. Don't forget to free all of these buffers when you're done with them. I haven't looked closely, but this approach might allow you to remove the temp variable.

@Banfa: I don't see why extarray would be out of scope at line 60.
Jan 6 '11 #4
Banfa
9,065 Expert Mod 8TB
@donbock

It wouldn't be that is a typo on my part.

All the pointers will end up pointing at the array ext defined on line 39 which will be out of scope at line 60.
Jan 6 '11 #5
donbock
2,426 Expert 2GB
@Banfa: The pointers in the array all end up pointing at the array temp defined on line 8. When I first looked at line 14 I thought there weren't enough parameters for sprintf. Then I realized that @boddah is counting on there being no conversion specifiers in format string a so that sprintf becomes functionally equivalent to strcpy.

Note to @boddah:
You are taking a big risk by relying on the assumption the configuration file doesn't contain percent characters. The consequences of encountering a malformed configuration file that contains a percent character is that your program will malfunction and possibly crash. A much safer way to use sprintf is to replace line 14 with:
Expand|Select|Wrap|Line Numbers
  1.     sprintf(temp,"%s",a);
As I mentioned earlier, the best approach is to use strcpy or strncpy instead of sprintf.
Jan 6 '11 #6

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

Similar topics

10
by: David Rasmussen | last post by:
If I have this struct S { int arr; }; and I do this: S s1,s2;
2
by: Don | last post by:
Using JS, how do I copy an associative array from one frame to another? Here's what I tried, and didn't work. In "main" frame referencing "header" frame: var cookies = new Object(); cookies...
12
by: Uncle | last post by:
I am an untrained hobbyist. Everything about programming I have learned from the internet. Thank you all for your gracious support. This is what I have: #define CONST_CHAR 0 void some_func(...
9
by: M Welinder | last post by:
This doesn't work with any C compiler that I can find. They all report a syntax error: printf ("%d\n", (int)sizeof (char)(char)2); Now the question is "why?" "sizeof" and "(char)" have...
15
by: Shuch | last post by:
Hi all, i m trying to read from a file and then copy it into an array...my code is as follow..it runs fine but i cant understand y it doesnt show me any output?? here is my code... using...
2
by: Potiuper | last post by:
Question: Is it possible to use a char pointer array ( char *<name> ) to read an array of strings from a file in C? Given: code is written in ANSI C; I know the exact nature of the strings to be...
1
by: MyCGal | last post by:
Hi, I have this code I wrote to copy any length lines into array of pointers. The problem is after storing the individual lines into the char pointer array, the dispaly() chops off some lines...
4
jlm699
by: jlm699 | last post by:
I've looked at the other articles about maps of maps and am still stuck on this! I'm trying to basically make an enumeration of a data monitoring app. Instead of displaying numbers for certain...
6
by: scoobydoo666 | last post by:
Hi Could any one tell me how to print size of char pointer array? for example char *ptrArray=new; cout<<sizeof(ptrArray); The above code will print 4 (pointer size) instead of...
1
by: helios | last post by:
Hi all, I'm resolved problem. and I want anybody need me that convert char to array bits char ConvertChar2ArrayBit(char ch) { char Bits; .... return Bits; } for...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.