I'm trying to read the following type of input
2
string1
string2
where the first line indicates the amount of strings following below, and the strings are all of (some) same length. Next, I'd like to print these strings in my program, which I was thinking of doing as follows.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void print_string_array(char** a, int size){
for (int i=0; i<size; i++){
printf("%s\n", a[i]);
}
}
int main()
{
int n;
scanf("%d", &n);
char* s;
scanf("%s", s);
int l = strlen(s);
char input[n][l];
strcpy(s, input[0]);
for (int i = 1; i < n; i++) {
scanf("%s", s);
strcpy(s, input[i]);
}
print_string_array(input, n);
}
But I get the following warnings and error.
main.c: In function ‘main’:
main.c:24:24: warning: passing argument 1 of ‘print_string_array’ from incompatible pointer type [-Wincompatible-pointer-types]
24 | print_string_array(input, n);
| ^~~~~
| |
| char (*)[(sizetype)(l)]
main.c:5:32: note: expected ‘char **’ but argument is of type ‘char (*)[(sizetype)(l)]’
5 | void print_string_array(char** a, int size){
| ~~~~~~~^
Segmentation fault (core dumped)
Why isn't my array input
recognized as a char**
type? And how would I go about fixing this without removing the general properties of my current program (for example, adaptability to any length of input strings)?
EDIT:
I've corrected some mistakes from not having coded in C for years (which may be a war crime from what I've seen in the comments):
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void print_string_array(char** a, int size){
for (int i=0; i<size; i++){
printf("%s\n", a[i]);
}
}
int main(){
int n;
scanf("%d", &n);
char s[100]; // large enough buffer
scanf("%s", s);
int l = strlen(s);
char input[n][l+1]; // +1 to leave room for ‘\0’ character?
strcpy(input[0], s);
for (int i=1; i<n; i++){
scanf("%s", input[i]);
}
print_string_array(input, n);
for (int i=0; i<n; i++){
free(input[i]);
}
free(input);
}
But I still get some errors and warnings which I would like to solve.
main.c: In function ‘main’:
main.c:22:24: warning: passing argument 1 of ‘print_string_array’ from incompatible pointer type [-Wincompatible-pointer-types]
22 | print_string_array(input, n);
| ^~~~~
| |
| char (*)[(sizetype)(n)]
main.c:5:32: note: expected ‘char **’ but argument is of type ‘char (*)[(sizetype)(n)]’
5 | void print_string_array(char** a, int size){
| ~~~~~~~^
Segmentation fault (core dumped)
Starting with the warnings, obviously I change the type of a
from char**
to something else. However, should I really give it the type char (*)[(sizetype)(n)]
?? Also, there's the problem of segmentaion fault
which is happening somewhere in the for loop.