Hi,please help...
It works fine when I define a 2-D array like char code[ROWS][SIZE].
But it won't work when I try to define the array dynamically using a
function. It just crashes.
Does anyone know why?
The compiler i'm using is Dev c++.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int file_length(FIL E *file);
void down_string(cha r *p);
char* issubstring(cha r *str1,char *str2);
char** dynamic_string_ array(int ROWS, int SIZE);
int main(void)
{
int row,n,i,coursef ound=0,ROWS,SIZ E,test;
FILE *datafile;
datafile=fopen( "3rdyear.cs v", "rb");
ROWS=file_lengt h(datafile);
printf("Has %d lines\n",ROWS);
char **Code,**Course ,**ClassSize,** Time1,**Time2,* *Room,c;
char search[30];
Code=dynamic_st ring_array(ROWS ,SIZE);
Course=dynamic_ string_array(RO WS,SIZE);
ClassSize=dynam ic_string_array (ROWS,SIZE);
Time1=dynamic_s tring_array(ROW S,SIZE);
Time2=dynamic_s tring_array(ROW S,SIZE);
Room=dynamic_st ring_array(ROWS ,SIZE);
for (row=0; row <ROWS; row++) {
test=fscanf(dat afile, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^\n]\n",
Code[row],Course[row],ClassSize[row],
Time1[row],Time2[row],Room[row]);
printf("row=%d, scanf converted %d (%s,%s,%s,%s,%s ,%s)\n",
row, test,
Code[row],Course[row],ClassSize[row],Time1[row],Time2[row],Room[row]);
}
printf("Please enter a name\n>");
scanf("%s",sear ch);
for(i=1; i<ROWS; i++) {
if(issubstring( Course[i],search)) {
coursefound=1;
printf("Course %s found!!\nTime 1 is %s\nTime2 is
%s\nVenue:%s",C ourse[i],Time1[i],Time2[i],Room[i]);
}
}
if(coursefound= =0) printf("No such Course!.\n");
fclose(datafile );
return EXIT_SUCCESS;
}
void down_string(cha r *p) //turns uppercase letters in a string to
lowercase
{
int i;
for(i=0;p[i]!='\0';i++)
{
if((p[i]>='A')&&(p[i]<='Z')) p[i]+=32;
}
}
char* issubstring(cha r *str1,char *str2) //checks if string2 is a
substring of string2
{
char tmp1[30],tmp2[30];
strcpy(tmp1, str1);
strcpy(tmp2, str2);
down_string(tmp 1); //turn it to lowercase
down_string(tmp 2);
return (strstr(tmp1, tmp2));
}
char** dynamic_string_ array(int ROWS, int SIZE)
{
char **array;
int i;
array=(char**) malloc(ROWS*siz eof(char));
for(i=0;i<ROWS; i++)
array[i]=(char *) malloc(SIZE*siz eof(char));
return array;
}
int file_length(FIL E *file)
{
int lines;
char dummy[100];
rewind(file);
lines=0;
while( fgets(dummy, 100, file) != NULL)
lines++;
rewind(file);
return(lines);
} 6 2299
In article <11************ **********@o13g 2000cwo.googleg roups.com>,
<dd************ *@yahoo.co.uk> wrote:
:It works fine when I define a 2-D array like char code[ROWS][SIZE].
:But it won't work when I try to define the array dynamically using a
:function. It just crashes.
:Does anyone know why?
:char** dynamic_string_ array(int ROWS, int SIZE)
:{
: char **array;
: int i;
: array=(char**) malloc(ROWS*siz eof(char));
You probably want malloc(ROWS*siz eof(char*))
seeing as you are going to be storing in character pointers.
: for(i=0;i<ROWS; i++)
: array[i]=(char *) malloc(SIZE*siz eof(char));
:
: return array;
:}
--
Would you buy a used bit from this man?? dd************* @yahoo.co.uk wrote: Hi,please help... It works fine when I define a 2-D array like char code[ROWS][SIZE]. But it won't work when I try to define the array dynamically using a function. It just crashes. Does anyone know why? The compiler i'm using is Dev c++.
#include <stdio.h> #include <stdlib.h> #include <string.h>
int file_length(FIL E *file); void down_string(cha r *p); char* issubstring(cha r *str1,char *str2); char** dynamic_string_ array(int ROWS, int SIZE);
int main(void) { int row,n,i,coursef ound=0,ROWS,SIZ E,test;
FILE *datafile; datafile=fopen( "3rdyear.cs v", "rb"); ROWS=file_lengt h(datafile);
printf("Has %d lines\n",ROWS);
char **Code,**Course ,**ClassSize,** Time1,**Time2,* *Room,c; char search[30];
Code=dynamic_st ring_array(ROWS ,SIZE);
SIZE has not been initialized. Perhaps your compiler could have been so
kind as to help you with that...
foo.c:12: warning: `SIZE' might be used uninitialized in this function
-David dd************* @yahoo.co.uk wrote: Hi,please help... It works fine when I define a 2-D array like char code[ROWS][SIZE]. But it won't work when I try to define the array dynamically using a function. It just crashes. Does anyone know why? The compiler i'm using is Dev c++.
Code snipped.
The code provided here does not compile. The code has numerous
errors. I think it would probably be best to take a step
back and rethink the problem. First, I would decide
on what data structure I need to store the data. Then
write functions that manipulate this data structure.
There are several ways to model the data structure.
Here is an example of one way.
First, make a struct where you can store the data for the class.
typedef struct CLASS
{
char *data;
char *code;
char *course;
char *size;
char *time1;
char *time2;
char *room;
} CLASS;
Then a struct that has as member, an array of class (ex. of the school)
and a member that represents the number of classes.
typedef struct CLASSARR
{
CLASS *class;
size_t cnt;
} CLASSARR;
Then write a function that will add a class and
a function that will print the class array. Test these
functions. Then add other functions that manipulates the data
structure one, or few, at a time, and test them out before
continuing. Then, if you come to a problem that you cannot
solve, the newsgroup can focus and better able to help you.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 100
typedef struct CLASS
{
char *data;
char *code;
char *course;
char *size;
char *time1;
char *time2;
char *room;
} CLASS;
typedef struct CLASSARR
{
CLASS *class;
size_t cnt;
} CLASSARR;
int AddCLASSARR(CLA SSARR *p, const char *s);
int ParseClassData( CLASS *p, char *data);
void PrintCLASSARR(C LASSARR *p);
void FreeCLASSARR(CL ASSARR *p);
int main(void)
{
CLASSARR myschool = {NULL};
FILE *fp;
AddCLASSARR(&my school,"3511,En glish,32,8:00am ,10:00am,130");
AddCLASSARR(&my school,"2511,Ca lculus,21,9:00a m,12:00am,141") ;
puts("\tTest Data");
PrintCLASSARR(& myschool);
FreeCLASSARR(&m yschool);
/* Test on a data file */
puts("\n\tData from a file");
if((fp = fopen("test.txt ","r")) != NULL)
{
char buf[MAXLINE];
size_t i;
for(i = 0 ; (fgets(buf,MAXL INE,fp)); i++)
if(!AddCLASSARR (&myschool,buf) )
printf("Error in File: Line %u\n",i+1);
fclose(fp);
PrintCLASSARR(& myschool);
FreeCLASSARR(&m yschool);
}
else puts("Unable to open the file to read data");
return 0;
}
int AddCLASSARR(CLA SSARR *p, const char *cs)
{
CLASS *tmp;
char *s;
if((s = malloc(strlen(c s)+1)) == NULL) return 0;
strcpy(s,cs);
tmp = realloc(p->class,(p->cnt+1)*sizeo f *tmp);
if(!tmp)
{
free(s);
return 0;
}
p->class = tmp;
if(!ParseClassD ata(&p->class[p->cnt],s))
{
free(s);
return 0;
}
p->cnt++;
return 1;
}
int ParseClassData( CLASS *p, char *data)
{
int i;
char *s, *tmp[6];
s = strtok(data,",\ n");
for(i = 0;(s);i++)
{
if(i < 6) tmp[i] = s;
s = strtok(NULL,",\ n");
}
if(i != 6) return 0;
p->code = tmp[0];
p->course = tmp[1];
p->size = tmp[2];
p->time1 = tmp[3];
p->time2 = tmp[4];
p->room = tmp[5];
p->data = data;
return 1;
}
void PrintCLASSARR(C LASSARR *p)
{
size_t i;
for(i = 0; i < p->cnt;i++)
printf("Code: %s\nCourse: %s\nSize: %s\n"
"Time1: %s\nTime2: %s\nRoom: %s\n\n",
p->class[i].code, p->class[i].course,
p->class[i].size,p->class[i].time1,
p->class[i].time2, p->class[i].room);
return;
}
void FreeCLASSARR(CL ASSARR *p)
{
size_t i;
for(i = 0; i < p->cnt; i++) free(p->class[i].data);
free(p->class);
p->class = NULL;
p->cnt = 0;
return;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email) http://www.geocities.com/abowers822/ ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes: In article <11************ **********@o13g 2000cwo.googleg roups.com>, <dd************ *@yahoo.co.uk> wrote: :It works fine when I define a 2-D array like char code[ROWS][SIZE]. :But it won't work when I try to define the array dynamically using a :function. It just crashes. :Does anyone know why?
:char** dynamic_string_ array(int ROWS, int SIZE) :{ : char **array; : int i; : array=(char**) malloc(ROWS*siz eof(char));
You probably want malloc(ROWS*siz eof(char*)) seeing as you are going to be storing in character pointers.
There's no need to cast the result of malloc() in C. (Two people in
this newsgroup will disagree with that; one has good reasons to write
code that compiles both as C and as C++, the other is wrong.)
It's also a good idea, in a malloc() call, to use the size of what the
result points to, not the size of a type that can change or that you
can get wrong.
The best way to do the above is:
array = malloc(ROWS * sizeof *array);
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Sorry i had sent the wrong version, so it had a few minor errors.
But the problem in question was solved by replacing sizeof(char) with
sizeof(*array) as you adviced.
Thanks.
Keith Thompson wrote: ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes: In article <11************ **********@o13g 2000cwo.googleg roups.com>, <dd************ *@yahoo.co.uk> wrote: :It works fine when I define a 2-D array like char
code[ROWS][SIZE]. :But it won't work when I try to define the array dynamically using
a :function. It just crashes. :Does anyone know why?
:char** dynamic_string_ array(int ROWS, int SIZE) :{ : char **array; : int i; : array=(char**) malloc(ROWS*siz eof(char));
You probably want malloc(ROWS*siz eof(char*)) seeing as you are going to be storing in character pointers. There's no need to cast the result of malloc() in C. (Two people in this newsgroup will disagree with that; one has good reasons to write code that compiles both as C and as C++, the other is wrong.)
It's also a good idea, in a malloc() call, to use the size of what
the result points to, not the size of a type that can change or that you can get wrong.
The best way to do the above is:
array = malloc(ROWS * sizeof *array);
-- Keith Thompson (The_Other_Keit h) ks***@mib.org
<http://www.ghoti.net/~kst> San Diego Supercomputer Center <*>
<http://users.sdsc.edu/~kst> We must do something. This is something. Therefore, we must do
this. dd************* @yahoo.co.uk wrote: char* issubstring(cha r *str1,char *str2) //checks if string2 is a substring of string2 { char tmp1[30],tmp2[30]; strcpy(tmp1, str1); strcpy(tmp2, str2); down_string(tmp 1); //turn it to lowercase down_string(tmp 2); return (strstr(tmp1, tmp2)); }
What happens when the strings are longer than 29 characters?
You'd be better off to roll your own stristr function that
doesn't need to allocate any memory. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Alex Vinokur |
last post by:
I have got two functions:
void foo1(char* str)
{
// Stuff
}
void foo2(int size)
{
char* str;
|
by: pozz |
last post by:
Hi all,
I want to use enum in this way:
typedef enum {
FIRST=1,
SECOND,
THIRD,
FORTH,
} order_t;
|
by: bvermeersch |
last post by:
Hello,
I found this in some else's code:
....
void write_E2(unsigned int address, unsigned char data)
{
EEADR = address;
EEADRH = (address >> 8);
//The EEADRH:EEADR register pair is used to address
//the data EEPROM for read and write operations.
|
by: lada77 |
last post by:
All,
Just wondering if one of you very helpful guru's out there could
comment on some odd behaviour I am seeing. I'm betting it is something
obvious but I am not experienced enough to tell right away. Here is my
code snippet and the results that I am seeing:
#include <map>
#include <iostream>
int
|
by: key9 |
last post by:
Hi all
on reading code I found these function
int foo(int char);
char foo(char ch_);
string foo(string ch);
| |
by: uche |
last post by:
Please give me some feed back on this issue:
Here is the complier error:
hexdmp.cpp: In function `void output(unsigned char, int, bool&)':
hexdmp.cpp:133: error: invalid types `unsigned char' for array
subscript
hexdmp.cpp:146: error: invalid types `unsigned char' for array
subscript
hexdmp.cpp:146: error: invalid types `unsigned char' for array
|
by: arnuld |
last post by:
this programme runs without any trouble. it took 45 minutes of typing.
i posted it here so that people can save their precious time:
// Stroustrup special edition
// chapter 4 exercise 2
// printing the sizes of different types
|
by: karthikbalaguru |
last post by:
Hi,
How is 'Int' Faster than 'Char' ?
I think , 'Char' is small and so it should be easily & efficiently .
Can someone here provide some info regarding this.
Thanks and Regards,
Karthik Balaguru
|
by: yithape |
last post by:
Hello ,
I have two differnt functions in C & in C++ . I want my variable in C++ program which is an array of characters & Integer if possible to be send to my c program. I tried using pointer but the moment control comes out of my C++ i loose all data in that array or i get garbage variables.
Can anyone please guide me for this issue. It will be really great !!
|
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: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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: 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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| | |