简体   繁体   中英

pointers to 2D arrays

I have a 2d array like this...

char a[][20]={"Hi","Hello","Bye","Good Morning"};

Now I need a char pointer to refer this array , modify one of the string in the array through pointer and print both modified array and array through pointer...

Modifications to array:

    strcpy(p+1,"Come");//copy string "Come" to array

    a[1][1]='O';//copy char 'O' index [1][1] 

ie.. Expected output:

Array: Hi COme Bye Good Morning

Pointer: Hi COme Bye Good Morning

I have a problem in assigning pointer to this array and printing array through pointer Please help...

If you want to turn your 2D array into something that is an array of pointer to char pointers, you are either going to have to allocate space for your char** on the stack in the local scope, or dynamically. If you go for the local scope approach, then you would need to simply create an array of char* , and then make each member of your array point to each string like so:

char a[][20]={"Hi","Hello","Bye","Good Morning", "" };

int total_strings = 0;
int index = 0;
while(strlen(a[index++])) total_strings++;

char* ptrs[total_strings];

for (int i = 0; i < total_strings; i++)
{
    ptrs[i] = a[i];
}

Now you can use the array of pointers like ptr[i][j] (where j is less than the length of the string at index i ), and if you need to pass it to a function by reference or assign it to another variable, the ptrs array would decay into a pointer, so you could pass ptrs as a char** to a function, or to another char** variable.

The next approach would be dynamic allocation of the pointer array ... that would look like the following:

char a[][20]={"Hi","Hello","Bye","Good Morning", "" };

int total_strings = 0;
int index = 0;
while(strlen(a[index++])) total_strings++;

//dynamic allocation of string pointer array 
char** ptrs = calloc(total_strings, sizeof(char*));

for (int i = 0; i < total_strings; i++)
{
    ptrs[i] = a[i];
}

//...more code
free(ptrs);

BTW, you can't do something as simple as char** ptr = a ... that is because of the way that C expects the memory for a char** to be laid out. In other words a char array[][] is actually a linear array in memory, even though it can be indexed as a two dimensional array. On the other hand a char** ptr is a variable that contains a memory address that is pointing to an array of pointers. So both ptr has to contain an address that points to a proper array of pointers, and every pointer ptr[i] needs to contain an address pointing to an array of char . Doing something as simple as char** ptr = a doesn't create the proper memory layout for that to happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM