-2

The below code outputs a segmentation fault :11

 #include<stdio.h>
 #include<string.h>
 int main(){
 char **total;
 strcpy(*(total+1),"hello");
 printf("%s",*(total+1));
 }

But while the below one(when initialised without **Array)

#include<stdio.h>
#include<string.h>
int main(){
char total[3][100];
strcpy(total[1],"hello");
printf("%s",total[1]);
} 

So what exactly went wrong in the first code? Is it due to the initialisation step or the strcpy function?

Fenil
  • 396
  • 1
  • 5
  • 16

2 Answers2

1

using char total[3][100] automatically reserve a part of memory for your array called total. using char **total you must allocate the memory for your array.

F.Guerinoni
  • 277
  • 2
  • 12
0

You haven't allocated the memory at all.

char **total = malloc(3*sizeof(char*));
for(int i=0; i!=3; ++i) total[i]=malloc(100*sizeof(char));

Do not forget to deallocate it:

for(int i=0; i!=3; ++i) free(total[i]);
free(total);

Accessing using pointer arithmetic does the same thing, however they can confuse readers. You can use the same array index syntax on pointers.

Also note that statically allocating using the array syntax is different from using pointers and malloc. The first allocates on stack, while the later is allocating on heap.

Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41