Find the answer to your Linux question:
Results 1 to 4 of 4
i've problem with my source code Code: #include<stdio.h> main() { int j; float t[100],dt,dx,*r; dt=0.01; dx=0.1; t[0]=0; { t[j]=t[j-1]+dt; *r=t[j]/(dx*dx); printf("t[%d] =%.2f\n",j,t[j]); printf("\n\nr[%d] =%.2f\n",j,*r); j++; } while(*r<=0.5); }...
  1. #1
    Just Joined!
    Join Date
    Mar 2010
    Posts
    1

    [help]segmentation fault

    i've problem with my source code
    Code:
    #include<stdio.h>
    
    main()
    {
    	int j;
    	float t[100],dt,dx,*r;
    
    	dt=0.01;
    	dx=0.1;	
    	t[0]=0;
    	
    	{
    		t[j]=t[j-1]+dt;
    		*r=t[j]/(dx*dx);
    		printf("t[%d] =%.2f\n",j,t[j]);
    		printf("\n\nr[%d] =%.2f\n",j,*r);
    		j++;
    	}
    	while(*r<=0.5);
    }

  2. #2
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    You didn't allocate or assign any memory to r...
    Make mine Arch Linux

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    The segfault is probably occurring because you didn't malloc r, like gerard said. However, you have other problems too.

    First, you don't initialize j. j will probably default to 0, but you should assign 0 to it initially.

    Also, I assume you're trying to use a do-while loop? You forgot the "do".
    DISTRO=Arch
    Registered Linux User #388732

  4. #4
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    The pointer variable is not pointing to any valid memory (float) address. This is why you are crashing. Better declaration:

    Code:
        float t[100],dt,dx,*r = (float*)malloc(sizeof(float));
    P.S. If this is a school exercise, please observe that the forums do not allow help with such - see the terms of use for details of what is allowed.
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...