Confusion in pointers in C
Hi all,
Here is another question for me that i could not find any answer. Try to create an dynamic array in C just using vscode in Ubuntu. Try to describe my issue in code sample below. When i run the code output is: [hello0][(null)]
When i use line 10 in code sample taking this error message "Exception has occurred Segmentation fault. Could you please tell me what i am doing wrong. I would be much appreciated.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int foo(char ***BufferArray,char *item,int idx);
int main(){
char **ptr=malloc(sizeof(char*)*3);
char a[]="hello0";
char b[]="hello1";
foo(&ptr,a,0);
//foo(&ptr,b,1);//Exception has occurred. Segmentation fault - line 10
printf("[%s]",*(ptr+0));
printf("[%s]",*(ptr+1));
getchar();
return(0);
}
int foo(char ***BufferArray,char *item,int idx){
int n;
n=1;
*(*(BufferArray+idx))=malloc(sizeof(char)*strlen(item));
strcpy(*(*(BufferArray+idx)),item);
return(0);
}