-1

i was new with array for C programming. Anybody can help me? I want to print all array that saved from the assignment. Please help!

#include <stdio.h>

int main(){
    const char *a[3];
    char s[100];
    int data, i=0;
    back:
    printf("Please insert name: ");
    scanf(" %s", &s);
    a[i] = s;
    printf("Do you want to add data?: ");
    scanf("%d", &data);
    if (data==1){
        i++;
        goto back;}
    else{
    printf("%s", a[0] , a[1] , a[2]);}
    return 0;
}
p1ai
  • 21
  • 9

2 Answers2

1

My suggestion would be never to use goto statement in C , it really mess up the readability of your source code. Also, go through this link, Why goto statement is not generally used.

Apart from this, you code can be simple re-written like this using for-loop statement.

#include <stdio.h>

int main(){
    char *a[3];
    char s[100];
    int data = 1, i;
    for(i=0; i<3 && data == 1; i++) {
      printf("Please insert name: ");
      scanf(" %s", &s);
      a[i] = s;
      printf("Do you want to add data?: ");
          scanf("%d", &data);
    }
    for(i=0; i<3; i++)
      printf("%s", a[i]);
    return 0;
}
Community
  • 1
  • 1
Bidisha Pyne
  • 543
  • 2
  • 13
0
#include <stdio.h>
int main()
{
    const char *a[3];
    char s[100];
    int data, i = 0, j;
    back: printf("Please insert name: ");
    scanf(" %s", &s);
    a[i] = s;
    printf("Do you want to add data?: ");
    scanf("%d", &data);
    i++;
    if (data == 1)
    {
        goto back;
    }
    else
    {
        for (j = 0; j < i; j = j + 1)
            printf("%s ", a[j]);
    }
    return 0;
}
mch
  • 9,424
  • 2
  • 28
  • 42
Ryuuk
  • 89
  • 1
  • 3
  • 14
  • 3
    Yes, the OP used label `back` and `goto back;`, but you shouldn't. – Jonathan Leffler May 18 '17 at 21:50
  • 1
    Also: This code is invalid and invokes undefined behaviour for various reasons! Your compiler should be crying, why do you ignore it? (I don't care if the errors are in the original, an answer should provide correct code) – too honest for this site May 19 '17 at 00:17
  • Also same when using this code, when i print, only the last array appear for three times. – p1ai May 19 '17 at 02:47