473,802 Members | 2,253 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to copy char * to char *array?

15 New Member
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 7602
Banfa
9,065 Recognized Expert Moderator Expert
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 Recognized Expert Top Contributor
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 Recognized Expert Top Contributor
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 Recognized Expert Moderator Expert
@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 Recognized Expert Top Contributor
@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
11404
by: David Rasmussen | last post by:
If I have this struct S { int arr; }; and I do this: S s1,s2;
2
1926
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 = parent.header.cookies; Actually, I'm having the same problem with copying a simple variable. The error message says the
12
5995
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( char* arg, int len ) { // stuff }
9
3026
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 identical precedence and right-to-left parsing, so why isn't the above equivalent to printf ("%d\n", (int)sizeof ((char)(char)2));
15
2555
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 namespace std; int Adj; //The matrix of adjacent nodes int curr; //it gives the current index to retrieve the neigbours of a node int n=100;
2
22614
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 read (the file will be written by only this program); file can be either in text or binary (preferably binary as the files may be read repeatedly); the amount and size of strings in the array won't be known until run time (in the example I have it in...
1
2168
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 while retains the others (mostly last and first line in the array). I guess there is some allocation problem but don't know where exactly. Please suggest. int readlines(char *lineptr, int maxlines) { int len, nlines,i; char *p,...
4
3277
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 variables I'd like to display a state. So I wanted to use maps for quick look-ups... anyway here's my code for filling and verifying the contents of my map of maps: include<map> #define MAX_LENGTH 80; void gen_enums(void) { char varname =...
6
35943
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 25. how do I print 25? Thanks in advance
1
2780
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 example: A after converted: 10000010
0
9699
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9559
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10529
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10301
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10058
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9107
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7596
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6835
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
2964
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.