What is the issue with this code (It is printing arr[0] correctly but I am getting issues with arr[1]… printing some weird characters):
using namespace std;
char ** setName() {
char * arr[2];
for (int i=0;i<2;i++)
arr[i] = (char*)malloc(100);
arr[0] = strdup("Robert");
arr[1] = strdup("Jose");
return arr;
}
int main()
{
char **arr;
arr = setName();
printf("First name is %s\n", arr[0]);
printf("Second name is %s\n", arr[1]);
return 0;
}
If it matters, i am running this code in Windows using Visual Studio 8.
You have two problems in that code:
An
autoarray such as yourchar * arr[2]is not automatically created withnew[]; its storage goes away when the function returns. This is the source of your garbage. You shouldmalloc()ornew[]it.strdup()does amalloc(), so you are pointlesslymalloc()ing storage that is then lost because you overwrite the pointer.