-2

im making a pointer array to strings and this issue happened

Is there anythings wrong with my code

char x[50];
int num = 0;
int i = 0;
char* arrs;
printf("Enter number");
scanf("%d", &num);
arrs = (char*)malloc(sizeof(char) * num);
getchar();
for (i = 0; i < num; i++)
{
    printf("Enter str number %d\n" , i);
    fgets(x, 50, stdin);
    *(arrs+i) = (char)malloc(sizeof(char) * strlen(x));
    strcpy((arrs+ i), x);
}
user23634623
  • 151
  • 5
  • 11

2 Answers2

0

arrs should be a "pointer to pointer to char", rather than simply a "pointer to char":

char x[50];
int num = 0;
int i = 0;
char **arrs;                            // <--- pointer to pointer
printf("Enter number:");
scanf("%d", &num);
arrs = malloc(sizeof (char *) * num);   // <--- sizeof (char *)
getchar();
for (i = 0; i < num; i++)
{
    printf("Entered str number %d\n", i);
    fgets(x, 50, stdin);
    arrs[i] = malloc(strlen(x) + 1);    // <--- +1 for the terminating '\0'
    strcpy(arrs[i], x);                 // <--- arrs[i] is a char *
}

// Do something

for (i = 0; i < num; i++)
{
    free(arrs[i]);
}
free(arrs);
nalzok
  • 14,965
  • 21
  • 72
  • 139
0

The problem is your are allocating memory for an array of chars not an array of String, this is char pointers. Just change sizeof(char) by sizeof(char *)

Nevado
  • 162
  • 7