• 0

Problem with pointers


Question

Hy there! Its my first time here, because i have not had a problem like this before. The program has a problem when i run it. When i choose "natakar" the second time and input the information it crashes. There is probably a problem with pointers or something in the function "elt natakar" but i do not know where, so if somebody could help me it would be a blessing;)

my code:

[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <Windows.h>[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]#define MIZ 77[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]typedef struct{
int miza;
char natakar[10];
char kuhar[10];
char jed[10];
SYSTEMTIME str_t;
int kolicina;
int status; //1...vneseno 2...pripravljeno
}narocilo;

typedef struct element{
narocilo narocilnica;
struct element *naslednji;
}elt;[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]elt *natakar(int *st){
elt *prvi;
elt *tmp;
elt *pom;

int i=*st;
char ime[10];
char jed1[10];

system("CLS");
tmp=(elt*)malloc(1*sizeof(elt));
pom=(elt*)malloc(1*sizeof(elt));
int temp=-1;
while((temp<1)||(temp>77)){
system("CLS");
printf("\tMeni NATAKAR:\n\n");
printf("Miza: ");
scanf("%d",&temp);
}
tmp -> narocilnica.miza = temp;
system("CLS");
printf("\tMeni NATAKAR:\n\n");
printf("Vase ime: ");
scanf("%s", ime);
strcpy(tmp -> narocilnica.natakar, ime);
strcpy(tmp -> narocilnica.kuhar, "?");
system("CLS");
printf("\tMeni NATAKAR:\n\n");
printf("Kaj bodo jedli: ");
scanf("%s", jed1);
strcpy(tmp -> narocilnica.jed,jed1);
temp=-1;
while ((temp<1)||(temp>20)){
printf("Koliko jedi: ");
scanf("%d",&temp);
system("CLS");
}
tmp -> narocilnica.kolicina = temp;
tmp -> narocilnica.status = 1;
tmp -> naslednji = NULL;
GetSystemTime(&tmp -> narocilnica.str_t);

if(i==0){
prvi=tmp;
prvi -> naslednji = NULL;
}
else{
pom = prvi;
while(pom -> naslednji != NULL){
pom = pom -> naslednji;
}
printf("konec zanke");
pom -> naslednji = tmp;
}

*st=*st+1;
return prvi;
system("PAUSE");
}

void kuhar(int *st, elt *prvi){
int i=*st;
int x=-1;
system("CLS");
printf("\tMeni KUHAR:\n\n");[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3] if(i==0){
printf("Trenutno se ni nobenih narocil.\n\n");
}
else{
elt *pom;
pom = (elt*)malloc(1*sizeof(elt));
pom = prvi;
printf("Pripravimo se na kuhanje...\n\n");
printf("NAROCILA: \n\n"); //dejmo izpisat vsa narocila
while (pom != NULL){
printf("\nMiza: %d", pom -> narocilnica.miza);
printf("\nJed: %s * %d",pom -> narocilnica.jed, pom -> narocilnica.kolicina);
if(pom -> narocilnica.status == 1) printf("\nStatus: SE NI SKUHANO");
if(pom -> narocilnica.status == 2) printf("\nStatus: Skuhal %s", pom->narocilnica.kuhar);
printf("\nMizo je stregel %s", pom -> narocilnica.natakar);
printf("\nDatum: %d.%d.%d \n\n",pom -> narocilnica.str_t.wDay,pom -> narocilnica.str_t.wMonth,pom -> narocilnica.str_t.wYear);

pom = pom -> naslednji;
}
}

system("PAUSE");
}[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]void meni(){
int x=-1;
elt *prvi;[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3] int st=0; //premikam se po tabeli

while (x!=0){
system("CLS");
printf("\nIzbirajte:\n\t(1) Natakar\n\t(2) Kuhar\n\t(3) EXIT\n");
printf("\n\tIzbira: ");
scanf("%d",&x);
if(x==1) prvi=natakar(&st);
else if(x==2) kuhar(&st, prvi);
}
free(prvi);
}[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3]int main(){
meni();
return 0;
}[/size][/font][/color]
[color=#000000][font=verdana, arial, helvetica, sans-serif][size=3][/CODE]

[/size][/font][/color]

Link to comment
https://www.neowin.net/forum/topic/1144774-problem-with-pointers/
Share on other sites

11 answers to this question

Recommended Posts

  • 0

What tools/platform are you using. On Windows you can run this in debug mode and it should catch crashes and allow you to debug. The same with gdb on Linux.

With both tools you can set breakpoints and then inspect the variable values. Might be a good idea to do so before the crash happens.

Also note that the -> operator is typically written as "p->attr"

  • 0

In my own opinion, the best thing to do in situations like this is to start commenting out section by section in your code and then start un-commenting until you find where it crashes.

Start printing out what your code is doing, which point is at etc. For instance: printf("Entering the while loop...\n\r"); printf("Accessing xyz\n\r"); <statement> printf("Accessing something else...\n\r"); and see where it stuffs up...

  • 0
  On 01/04/2013 at 10:55, rwx said:

In my own opinion, the best thing to do in situations like this is to start commenting out section by section in your code and then start un-commenting until you find where it crashes.

Start printing out what your code is doing, which point is at etc.

i have done that, it crashes at this point:


while(pom -> naslednji != NULL){
pom = pom -> naslednji;
}
printf("it does not come to here");
[/CODE]

and i do not know where the problem is...

  • 0
  On 01/04/2013 at 10:57, computerboy1001 said:

i have done that, it crashes at this point:


while(pom -> naslednji != NULL){
pom = pom -> naslednji;
}
printf("it does not come to here");
[/CODE]

and i do not know where the problem is...

Well it looks like you have an infinite loop there.

  Quote
pom -> naslednji != NULL

pom->naslednji[b] never [/b]becomes [b]NULL [/b]therefore the condition always evaluates to [b]true[/b] and the loop never ends. That's why the statement after the loop never runs.

  • 0
  On 01/04/2013 at 11:07, rwx said:

Well it looks like you have an infinite loop there.

pom->naslednji never becomes NULL therefor the loop never ends. That's why the statement after the loop never runs.

how can it not become NULL, i have assigned prvi->naslednji=NULL and then said pom=prvi, so therefore it shoud come to NULL, shouldnt it?

  • 0

Oh, there you have it. DON'T EVER USE DEVC++ *AHEMM* *AHERR* *cough*... sorry for that. Seriously, though, please don't. Debugger will show you why - it will crash more than your program would.

A basic linked list exercise here, but the variable naming and the occasional formatting voes made it a complete mess to read through.

With that I try to hide my own ignorance on the topic, har har har.

  • 0
  On 01/04/2013 at 10:42, computerboy1001 said:

I am programming in Windows 7, in DevC++.

I do not know how to use a debugger...

Could you please help me???

Do yourself a favor and use Visual Studio Express Desktop instead. When you launch your program normally in Visual Studio, (i.e. via the F5 shortcut or Debug->Run), you are automatically using a debugger which will break by itself on the line where the crash is happening and allow you to inspect the value of every variable. You can also very easily step through your code line by line and see exactly what is happening to every variable as the program execute.

DevC++ is apparently not abandoned anymore, there's a single dev working on it, but it's probably still not very good.

  • Like 2
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Glow 25.08 by Razvan Serea Glow provides detailed reporting on every hardware component in your computer, saving you valuable time typically spent searching for CPU, motherboard, RAM, graphics card, and other stats. With Glow, all the information is conveniently presented in one clean interface, allowing you to easily access and review the comprehensive hardware details of your system. Glow provides detailed information on various system aspects, including OS, motherboard, processor, memory, graphics card, storage, network, battery, drivers, and services. The well-organized format ensures easy access to the required information. You can export all the gathered data to a plain text file, facilitating sharing with others for troubleshooting purposes. No installation needed. Just decompress the archive, launch the executable, and access computer-related information. Glow runs on Windows 11 and Windows 10 64-bit versions. Glow 25.08 release notes: What's new Glow's render engine has been improved. The program now supports high-resolution displays even on multi-monitor setups and monitors with varying DPI levels. It delivers sharp and clear visuals on 8K and higher DPI screens. The TSImageRenderer algorithm has been integrated into Glow. All visual icons in the interface are now automatically resized in a DPI-aware manner, ensuring high-resolution display quality. We know that Glow's Installed Drivers and Installed Services sections load slowly. That's why the loading algorithms have been reprogrammed into a parallel structure. Now it loads with up to 95% speed increase compared to the processor core. Glow's monitor testing tools have been reprogrammed. The Dead Pixel Test and Dynamic Color Range Test now function with improved accuracy. The Screen Overlay Tool has been redesigned, featuring theme sensitivity and new functions such as a close button. The startup engine for all Glow tools has been redeveloped, allowing for more efficient and effective management of the tools. The search engine's clear button in the "Installed Drivers", "Installed Services" and "Installed Applications" sections has been refreshed with a DPI-aware design for enhanced visibility. Icons have been added to the BIOS Update, Battery Report Generation, and Export buttons. Icons have been added to all buttons across Glow's tools. The Tab key functionality in Glow's interface has been improved, enabling more precise and stable navigation between elements. Glow's logo has been updated with a new design, offering a more elegant and modern appearance. Glow's primary colors have been redesigned within the Adobe RGB Color Space, giving the interface a more contemporary look. The About section has been reprogrammed. All social media buttons now feature icons, and the close button is DPI-aware and more prominent. Fixed Bugs Fixed an issue causing control buttons to overlap and shift position at high DPI settings. Resolved a DPI-related issue where checkmarks in the top menu distorted visually at high DPI values. Fixed a parallel processing error that caused the program to crash after clicking and closing information text in any monitor test tool. Corrected a bug in the Dynamic Color Range Tool that caused white space to appear on the right and bottom when resizing. Fixed calculation errors affecting the color scale and ratios in the Dynamic Color Range Tool. Resolved a layering issue that sometimes caused message boxes to appear behind the program window. Changes The backend code structure of Glow has been improved to a modular architecture, ensuring full compatibility and easier integration with other Türkay Software products. Tools have been moved back to the top menu. Some interface icons have been replaced to provide better visual clarity. A YouTube link has been added to the About section. Note: Always unzip the program before using it. Otherwise you may get an error. Download: Glow 25.08 | 3.1 MB (Open Source) View: Glow Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Vivaldi 7.5.3735.56 by Razvan Serea Vivaldi is a cross-platform web browser built for – and with – the web. A browser based on the Blink engine (same in Chrome and Chromium) that is fast, but also a browser that is rich in functionality, highly flexible and puts the user first. A browser that is made for you. Vivaldi is produced with love by a founding team of browser pioneers, including former CEO Jon Stephenson von Tetzchner, who co-founded and led Opera Software. Vivaldi’s interface is very customizable. Vivaldi combines simplicity and fashion to create a basic, highly customizable interface that provides everything a internet user could need. The browser allows users to customize the appearance of UI elements such as background color, overall theme, address bar and tab positioning, and start pages. Vivaldi features the ability to "stack" and "tile" tabs, annotate web pages, add notes to bookmarks and much more. Vivaldi 7.5.3735.56 changelog: [Chromium] Update to 138.0.7204.173 Download: Vivaldi 64-bit | 123.0 MB (Freeware) Download: Vivaldi 32-bit | ARM64 View: Vivaldi Home Page | Screenshot | Release Notes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Floorp 11.29.0 by Razvan Serea Floorp is a cutting-edge web browser that combines the trusted foundation of Mozilla's Firefox with a unique Japanese perspective, offering users an exceptional online experience. This open-source browser prioritizes privacy, customization, and security. Floorp is transparent, with no user tracking or data sharing, and it's completely open source. With a strict no-tracking policy and full transparency, your personal information remains private. As an open-source project, Floorp not only shares its source code but also its build environment, inviting users to contribute and build their unique versions. The regular updates, based on Firefox ESR, ensure that you always have the latest features and security enhancements. Get to the point with Floorp Lightning's minimalism With a keen eye on user preferences, Floorp is gearing up to launch "Floorp Lightning," a streamlined and performance-focused browser, harkening back to the fundamentals of web browsing. This browser has undergone a meticulous transformation, shedding more than 80% of the features that characterized its predecessor. What remains are only the high-demand functionalities within the Floorp ecosystem. The result is a sleek, lean, and swift web browser optimized for maximum efficiency. In the ever-accelerating digital world, "Floorp Lightning" is poised to offer users a refreshingly nimble and responsive browsing experience, set to debut in beta mode this November. Floorp key features: Strong Tracking Protection: Floorp offers robust tracking protection, safeguarding users from malicious tracking and fingerprinting on the web. Flexible Layout: Customize Floorp's layout to your heart's content, including moving the tab bar, hiding the title bar, and more for a personalized browsing experience. Switchable Design: Choose from five distinct designs for the Floorp interface, and even switch between OS-specific designs for a unique look Regular Updates: Based on Firefox ESR, Floorp receives updates every four weeks, ensuring up-to-date security even before Firefox's releases. No User Tracking: Floorp prioritizes user privacy by abstaining from collecting personal information, tracking users, or selling user data, with no affiliations with advertising companies. Completely Open Source: The full source code for Floorp is open to the public, allowing transparency and enabling anyone to explore and build their own version. Dual Sidebar: Floorp features a versatile built-in sidebar for webpanels and browsing tools, making it perfect for multitasking and quick access to bookmarks, history, and websites. Flexible Toolbar & Tab Bar: Customize your browser with Tree Style Tabs, vertical tabs, and bookmark bar modifications, catering to both beginners and experts in customization. User-Centric Web Experience: Floorp prioritizes user privacy and collaboratively blocks harmful trackers. Floorp 11.29.0 changelog: Security fixes Download: Floorp 64-bit | 85.2 MB (Open Source) Links: Floorp Website | Github Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • "ethical", what an interesting term. Subjectively objective but objectively subjective. I argue there are very few "ethics" in copyright. Hell, I see very few applications of true ethics in anything. I see a great deal of unethical actions being done under the guise of ethics however. How unethical... I greatly prefer open source LLMs. Copyright ethics are mickey mouse deep.
  • Recent Achievements

    • Collaborator
      fernan99 earned a badge
      Collaborator
    • Collaborator
      MikeK13 earned a badge
      Collaborator
    • One Month Later
      Alexander 001 earned a badge
      One Month Later
    • One Month Later
      Antonio Barboza earned a badge
      One Month Later
    • Week One Done
      Antonio Barboza earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      592
    2. 2
      ATLien_0
      225
    3. 3
      Michael Scrip
      167
    4. 4
      Xenon
      139
    5. 5
      +FloatingFatMan
      128
  • Tell a friend

    Love Neowin? Tell a friend!