Reputation:
I am going to prompt the user to enter their street name (is a single word) and separated by a space, their house number. The user will give me 10 of these at the prompt.
I am going to put the street name into one array, and the house number into another. So far I have the code shown below. It results in a segmentation fault. I have read all of my notes and I am still unsure why this is happening. Any help is greatly appreciated. (Note, the second loop was to see if the street array was correctly storing its elements).
#include <stdio.h>
int main (void){
char *street[10];
int *number[10];
int i;
for (i=0;i<10;i++){
printf("Enter street and number: \n");
scanf(" %s %d", street[i], number[i]);
}
for (int i=0;i<10;i++){
printf("%s ",street[i]);
}
}
Upvotes: 0
Views: 46
Reputation: 3355
Angela, you have mainly made 3 mistakes in your code .
First to have an integer array of 10 elements int number[10];
not int *number[10];
.Here you need only a one dimensional array. int *number[10];
Is used for two dimensional array.
Second you cannot use string pointer without allocating memory for that.so the allocation code using malloc street[i] = (char *)malloc(sizeof(char) * 100);
should be used before reading some values to street[i]
.
Third while scanning an integer array in c you have to use the &
operator.So the scanf
statement should be scanf("%s%d", street[i], &number[i]);
Please try this modified code.This will work:-
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *street[10];
int number[10]; // not *number[10]
int i;
for (i = 0; i < 10; i++)
{
printf("Enter street and number: \n");
street[i] = (char *)malloc(sizeof(char) * 100); // assuming the max-string size is 100
scanf("%s%d", street[i], &number[i]); // not number[i]
getchar(); // for handling un managed '\n' (enter-keys)
}
for (int i = 0; i < 10; i++)
{
printf("%s\n", street[i]);
}
}
Upvotes: 1
Reputation: 1392
C needs 2-dimensional array for storing strings.
#include <stdio.h>
int main (void) {
char street[10][100];
int number[10];
int i;
for (i=0;i<3;i++){
printf("Enter street and number: \n");
scanf("%99s %d", &street[i], &number[i]);
}
for (int i=0;i<3;i++) {
printf("%s ",street[i]);
}
}
or with pointers, you could use malloc to allocate memory
#include <stdio.h>
int main (void) {
char *street[10];
int number[10];
int i;
for (i=0;i<3;i++){
street[i] = malloc(100);
printf("Enter street and number: \n");
scanf("%99s %d", street[i], &number[i]);
}
for (int i=0;i<3;i++) {
printf("%s ",street[i]);
}
}
Upvotes: 1