I know this question has been answered but I have some more problems with it and I have read the other answers of passing pointer to a pointer but I can't figure out how to access the values or store them.
Also code gives error Segmentation fault (core dumped)
#include <stdio.h>
#include<stdlib.h>
void secValue(char **);
void main(){
char *pointer=(char *)malloc(2*sizeof(char));
char a;
int i;
printf("Enter 1st value \n");
scanf(" %c",&pointer[0]);
secValue(&pointer);
//Display
for(i=0;i<=3;i++){
printf(" %c\n", pointer[i]);
}
}
void secValue(char **pointera){
printf("First value is %c \n",*pointera[0]);
printf("Enter 2nd value\n");
scanf(" %c",&pointera[1]);
printf("Enter 3rd and 4th value\n");
*pointera=(char *)realloc(*pointera,3*sizeof(char));
scanf(" %c %c",&pointera[2],&*pointera[3]);
}
You need to use &((*pointera)[1])
instead of &pointera[1]
because the second expression is address of second pointer in pointera array, NOT the address of nested pointer address. We must use parentheses because of operator priority.
I also included minor code fixes such as removing redundant pointer casts. C language allows implicit casts from void *
to other pointer types.
You must also correct argument in realloc()
function call. You access third array index, so array length must be at least 4.
You must also insert getchar()
calls after reading each single char by scanf() function, because scanf()
leaves \n character in stdin, and next call to scanf()
with %c format will read new line character instead of typed character by you.
So there is your whole code (fixed), I tried not to change logic and even names :P
#include <stdio.h>
#include <stdlib.h>
void secValue(char **);
int main() {
char *pointer = malloc(2 * sizeof(char));
char a;
int i;
printf("Enter 1st value \n");
scanf("%c", &pointer[0]);
getchar();
secValue(&pointer);
for(i = 0; i <= 3;i++) {
printf("%c\n", pointer[i]);
}
}
void secValue(char **pointera) {
printf("First value is %c\n", (*pointera)[0]);
printf("Enter 2nd value\n");
scanf("%c", &((*pointera)[1]));
getchar();
printf("Enter 3rd and 4th value\n");
*pointera = realloc(*pointera, 4 * sizeof(char));
scanf("%c %c", &((*pointera)[2]), &((*pointera)[3]));
}
Cheers, gjm