Naishadh Vora
Naishadh Vora

Reputation: 13

Loop closes unexpectedly

I checked this but it didn't help - For loop scans one less time in c So, I'm new to programming and I was trying to solve this question from SPOJ (my doubt is general and hence didn't post it in SPOJ forums). http://www.spoj.com/problems/STRHH I made and ran this code in CodeBlocks using GCC where it runs as intended but runs differently when I ran it through Ideone.

#include<stdio.h>
#include<malloc.h>
#include<string.h>
int main()
{
    int n,i,length,j;
    char **ptrarray; //creating a pointer array that holds addresses of the strings  
    fscanf(stdin,"%d",&n);
    ptrarray = (int *)malloc(n*sizeof(int)); //dynamically allocating memory for 'n' strings and storing their addresses in 'ptrarray'
    for (i=0;i<=n;i++)
        ptrarray[i] = (char *)malloc(201); //dynamically allocating memory for the strings
    for (i=0;i<=n;i++)
        fgets(ptrarray[i],201,stdin); //receiving string
    for (i=0;i<=n;i++)
    {
        length=strlen(ptrarray[i])-1; //string length
        for (j=0;j<(length)/2;j+=2) //obtain every other character up to half of the string length
            printf("%c",ptrarray[i][j]);
        printf("\n");
    }
    return 0;
}

Input:

4
your 
progress 
is 
noticeable

Expected Output:

y
po
i
ntc

So, I get the expected output when I run it in Codeblocks but when running it on ideone (and submitting it on SPOJ), the printf loop only runs thrice instead of 4 times and the output I get is:

y
po
i

My question is why I'm not getting the fourth "ntc" in ideone and why is it not being accepted?

Edit: Changed "200" to "201" bytes, used fscanf instead of scanf, removed fflush and updated loop condition. So, I get the required answer if I change loop condition from '

Upvotes: 1

Views: 69

Answers (1)

unwind
unwind

Reputation: 399743

This:

char **ptrarray; //creating a pointer array that holds addresses of the strings  
scanf("%d",&n);
ptrarray = (int *)malloc(n*sizeof(int)); //dynamically allocating memory for 'n' strings and storing their addresses in 'ptrarray'

Makes no sense; you're allocating space for n integers, but assigning the result to a pointer to a pointer (neither of which is the same size as an integer, in general).

The allocation should be:

ptrarray = malloc(n * sizeof *ptrarray);

This will allocate n times the size of whatever ptrarray points at, i.e. sizeof (char *), but without repeating any type names.

This is a quite general and much safer pattern, worth learning.

As mentioned in the comment, don't fflush(stdin);, it's undefined behavior.

Upvotes: 4

Related Questions