Masoud Masoud - 3 years ago 138
C Question

creating table with char pointers

I want to create a table in c with char pointers but this program doesn't work and I don't know where is problem

should I put '\0' at the end of string ?

Here is my code :

void table(int n)
{
char *s,*first;
s = (char *)malloc((5*n+3)*sizeof(char));
first = s;
int i,j;
for(i=0;i<2*n+1;i++)
{
for(j=0;j<3*n+1;j++)
{
if(i%2==0 && j%3==0)
{
*s = ' ';
s++;
}
else if(i%2==0 && j%3!=0)
{
*s = '-';
s++;
}
else if(i%2==1 && j%3==0)
{
*s = '|';
s++;
}
else if(i%2==1 && j%3 != 0)
{
*s = ' ';
s++;
}


}
*s = '\n';
s++;
}
*s = '\0';
printf("%s",first);
free(s);
}


table like this :

-- --
| | |
-- --
| | |
-- --


Edit:
after some edit in program now it run but in some cases program crash and windows stop program running .

Answer Source

The amount of iterations is incorrect.

I think you have more iterations than you expect. Put a counter in the iterations and you'll see.

Look:

If n=3:

  • Malloc takes 18 chars.
  • first for iterates 7 times.
  • second for iterates 10 times.
    • total iterations is not 7+10, it's 7*10

You are writing out of space, aren't you?

This is the malloc you are looking for:

s = (char *)malloc(( (2*n+1) * (3*n+2) )*sizeof(char));
  • 2n+1 for the vertical space of the square.
  • 3n+1 for the horizontal space + 1 for the \n and the \0 in the last line (no \n there).

This is the full code:

#include<stdlib.h>
#include<stdio.h>

void table(int n);
int main(void){
    table(10);
    return 0;
}

void table(int n)
{
    char *s,*first;

    s = (char *)malloc(( (2*n+1) * (3*n+2) )*sizeof(char));

    if(!s){
        return;
    }

    first = s;
    int i,j;
    for(i=0;i<2*n+1;i++)
    {
        for(j=0;j<3*n+1;j++)
        {
            if(i%2==0 && j%3==0)
            {
                *s = ' ';
                s=s+sizeof(char);
            }
            else if(i%2==0 && j%3!=0)
            {
                *s = '-';
                s=s+sizeof(char);
            }
            else if(i%2==1 && j%3==0)
            {
                *s = '|';
                s=s+sizeof(char);
            }
            else if(i%2==1 && j%3!= 0)
            {
                *s = ' ';
                s=s+sizeof(char);
            }
        }
        *s = '\n';
        s++;
    }

    *s = '\0';
    printf("%s",first);
    free(first);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download