0

I am trying to point to the letter 'o' in the string 'orange', but I don't know how to do it.

Here is what I have written:

char* pstrarray[150];
int main()
{
   char buffer[50];
   int test; scanf("%d", &test);
   for (int i = 0; i < test; i++)
   {
      scanf("%s", buffer);
      strcpy(pstrarray[i], buffer);
   }
}
Sarah
  • 39
  • 3
  • 4
    `pstrarray` is an array of pointers. But since you define it in the file-scope (outside of any functions) all those pointers will be *null*. Dereferensing null pointers (which will happen in your `strcpy` call) leads to *undefined behavior*. Perhaps you should have an array of arrays instead, as in `char pstarray[150][50];`? – Some programmer dude Apr 14 '21 at 06:03

1 Answers1

2

As pointed out by @SomeProgammerDude in comment, you're having an uninitialized char* pstrarray[150] which contains NULL values. I tried running your code and it was giving segmentation fault:

c-posts : $ gcc pointtoorange.c 
c-posts : $ ./a.out 
2
rohan
Segmentation fault (core dumped)

You should use an array of arrays, either fixed char pstrarray[150][50] or you can also allocate dynamically:

char **pstrarray;
int main() {
   char buffer[50];
   int test; 
   scanf("%d", &test);
   // Allocate memory for array
   pstrarray = (char **) malloc(sizeof(char *) * test);
   for (int i = 0; i < test; i++) {
       pstrarray[i] = (char *) malloc(sizeof(char) * 50);
   }

You should then be able to store various values recieved in input loop to pstrarray:

for (int i = 0; i < test; i++) {
  scanf("%s", buffer);
  strcpy(pstrarray[i], buffer);
}

// Print result
for (int i = 0; i < test; i++) {
   printf("%s\n", pstrarray[i]);
}

I tested and it seemed to be working okay:

c-posts : $ ./a.out 
3
orange
guava
mango
orange
guava
mango
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40