Leslie Pu
Leslie Pu

Reputation: 21

How to handle array of pointer in C?

Like I declared an array of pointer in a loop and use to it collect a bunch of strings by scanning, but after the loop when I want to print out the strings in the array, I found that all arrays are occupied by the same string, which is the latest one I input. The code is as following

#include<stdio.h>

int main(){

char *array[3];
char content[10];
int time;
scanf("%d",&time);

for(int i=0;i<time;i++){
  scanf("%s",content);
  array[i]=content;


}

for(int j =0;j<time;j++){
  printf("%s\n",array[j]);
}

return 0;}

Upvotes: 0

Views: 176

Answers (2)

TruthSeeker
TruthSeeker

Reputation: 1579

On every iteration input stream is copied to content and address of content is stored in array. Hence content is overwritten again and again and address is copied to every index of array

for(int i=0;i<time;i++){
  scanf("%s",content);
  array[i]=content; //Here every array[0..time] is assigned with address of content
}

Which in short behaving as follows,

enter image description here

what you need is new storage location for every iteration which either dynamically allocated through malloc from heap as follows,

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    int i;
    char content[10];
    int n;
    scanf("%d", &n);
    char*array[n];
    for (i = 0; i < n; i++) {
        scanf("%9s", content); //ensure no more than 10 letter added includeing '/0'
        char*c = malloc(strlen(content)); 
        if(c)
        {
            strncpy(c,content,strlen(content));
            array[i] = c;
        }
        else
        {
            exit(0);
        }
    }

    for (i = 0; i < n; i++) {
        printf("%s\n", array[i]);
    }

    for (i = 0; i < n; i++) {
        free(array[i]);
    }

}

or through VLA's as follows,

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    int i;
    int n;
    scanf("%d", &n);
    char*array[n];
    char content[n][10];
    for (i = 0; i < n; i++) {
        scanf("%9s", content[i]);
        array[i] = content[i];
    }

    for (i = 0; i < n; i++) {
        printf("%s\n", array[i]);
    }
}

Upvotes: 1

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

You have an array of pointers. You still need to allocate memory for each array.

for(int i=0;i<time;i++){
  ret = scanf("%s",content);
  if (ret == 0) { exit(1); // handle error}
  array[i] = malloc(strlen(content)+1);
  if (array[i] == NULL) {  exit(1); // handle error}
  strcpy(array[i],content);
}

Remember to free at the end

for (int i=0; i<time; i++)
{
  free(array[i]);
}

Upvotes: 0

Related Questions