I have a homework that's supposed to ask the user for a number and make a square with the length being the number they put. If the user types in 5, then the program needs to make a square that is 5x5.
When I compile it, i get a segmentation fault (core dumped). I have no idea where the problem is. Can you guys help me? I even tried running the program with paper and pencil to see what my output would be and it seemed fine to me.
#include <stdio.h>
int main (){
int size, limit = 0;
char ch = 'A';
int rows = 1;
printf("Enter size:\n");
scanf("%d", size);
while (limit <= size){
if (rows == 1 || rows == size){ /* This only works in first and last row */
printf("%c", ch);
limit++;
}
if (rows != 1 && rows != size){ /* This only works if row is not 1 and last row*/
do{
printf("%c", ch);
limit++;
do {
printf(" ");
limit++;
} while (limit != size -1);
limit++;
if (limit == size){
printf("%c", ch);
rows++;
limit = 0;
printf("\n");
}
}while (rows != 1 && rows != size); /* while not in first AND last row */
}
Enable your compile warnings, this is wrong.
scanf("%d", size);
& is missing in scanf statement
scanf("%d", &size);
You are passing an
int
to scanf, pass its address like soYou are passing the wrong argument to
scanf
. You are passing an integer but what you need to pass is a pointer to allocated storage where the interpretation of the extracted characters is stored in memory.For accomplishing this, remember the
&
(ampersand), the address-of operator, is what you use in C to get a memory address. So in other words, what you must pass toscanf
is the address-of the variable that you want to use to store the data.