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 开发者_Python百科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
auto
array 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.char **arr = malloc(2 * sizeof (*char));
strdup()
does amalloc()
, so you are pointlesslymalloc()
ing storage that is then lost because you overwrite the pointer.
You are returning the address of a local variable. arr
doesn't exist after setName
exits, so main
's arr
is pointing to bad memory.
You'd be better off writing straight into main
's arr
by passing it as a parameter to setName
:
using namespace std;
void setName(char* (&arr)[2]) {
for (int i=0;i<2;i++)
arr[i] = (char*)malloc(100);
arr[0] = strdup("Robert");
arr[1] = strdup("Jose");
}
int main()
{
char * arr[2];
setName(arr);
printf("First name is %s\n", arr[0]);
printf("Second name is %s\n", arr[1]);
return 0;
}
Your array of pointers is local to your setName function.
Try something like:
char ** setName() {
char ** arr = (char **)malloc(2 * sizeof(char *));
for (int i=0;i<2;i++)
arr[i] = (char*)malloc(100);
strcpy(arr[0], "Robert");
strcpy(arr[1], "Jose");
return arr;
}
... and don't forget to free
what you malloc
.
You're returning the address of arr. This is undefined behavior and you really don't know what's going to happen. I would strongly suggest you add a parameter to that function by reference and just pass arr to it from main instead of returning.
Your code can be something like this:
char *setName() {
char * arr[2];
static int j=0;
int i=0;
for (i=0;i<2;i++)
arr[i] = (char*)malloc(100);
strcpy(arr[0],"Robert");
strcpy(arr[1],"Jose");
return arr[j++];
}
int main(){
char *arr1,*arr2;
arr1 = setName();
arr2 = setName();
printf("First name is %s\n", arr1);
printf("First name is %s\n", arr2);
return 0;
}
精彩评论