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.. -
#include <stdio.h>
-
#include <stdlib.h>
-
-
#include <string.h>
-
#include <mysql.h>
-
#define MAXLENGTH 1024
-
char *extarray[20];
-
char temp[50];
-
int add2array(char*,int);
-
-
int add2array(char *a, int b)
-
{
-
printf("add2array...\n");
-
sprintf(temp,a);
-
extarray[b] = temp;
-
return 0;
-
}
-
int main( int argc, char *argv[] )
-
-
{
-
-
char *v_file = "/home/abuser/configpolicy.txt";
-
-
char *token;
-
char line[256];
-
int linenum = 0;
-
FILE * _file;
-
-
int a;
-
-
// THIS PART GETS THE DETAILS FROM config file
-
-
_file = fopen(v_file, "r");
-
if(_file == NULL)
-
return -1;
-
-
while(fgets(line, 256, _file) != NULL)
-
{
-
char ext[256];
-
if(sscanf(line,"%s", ext) != 1)
-
{
-
fprintf(stderr, "syntax err-line %d\n", linenum);
-
continue;
-
}
-
-
token = strtok(ext,";");
-
a=0;
-
while(token!=NULL)
-
{
-
//getDirHash(token);
-
//extarray[linenum]=token;
-
if(a == 0)
-
add2array(token,linenum);
-
token = strtok(NULL,";");
-
a++;
-
}
-
linenum++;
-
}
-
// END
-
for(a=0;a<4;a++)
-
printf("array %d is %s\n", a,extarray[a]);
-
return 0;
-
-
}
-
This is the config file's content: -
.txt;new;delete
-
-
.txt;tamper;restore
-
-
.exe;new;delete
-
-
.exe;tamper;restore
-
This is the output of the code: -
add2array...
-
.txt
-
add2array...
-
.txt
-
add2array...
-
.exe
-
add2array...
-
.exe
-
array 0 is .exe
-
array 1 is .exe
-
array 2 is .exe
-
array 3 is .exe
-
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.
horace1 1,510
Recognized Expert Top Contributor
following on from comment by banfa you could do something like -
char extarray[20][80];
-
-
int add2array(char *a, int b)
-
{
-
printf("add2array...\n");
-
sprintf(temp,a);
-
strcpy(extarray[b],temp);
-
return 0;
-
}
-
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.
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.
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:
As I mentioned earlier, the best approach is to use strcpy or strncpy instead of sprintf.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: David Rasmussen |
last post by:
If I have this
struct S
{
int arr;
};
and I do this:
S s1,s2;
|
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
|
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
}
|
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));
|
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;
| |
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...
|
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,...
|
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 =...
|
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
|
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
|
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...
| |
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,...
|
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...
|
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...
|
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...
|
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...
|
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...
| |
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();...
|
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...
| |