0

I'm currently refreshing my C skills and having trouble with the following code:

int main (int argc, const char * argv[]) {

    @autoreleasepool {

        int numberOfTestCases;

        scanf("%d", &numberOfTestCases);

        char *a[numberOfTestCases];

        for (int i = 0; i < numberOfTestCases; i++) {

            char input[100];
            scanf("%s", input);
            a[i] = input;
        }

        for (int k = 0; k < numberOfTestCases; k++) {
            printf("%s\n", a[k]);
        }

    }
    return 0;
}

First I want to enter the user a number to determine how many strings she/he wants to enter.

Second I want to let the user enter the number of strings and store them in an array of strings.

Last I want to loop over that array and print out all the values. So my test input is e.g. something like:

5

My

name

is

John

Doe

with an expected result of

My

name

is

John

Doe

Instead the result is:

Doe

Doe

Doe

Doe

Doe

I can't figure out how to insert the input in the array.. very thankful for a hint in the right direction.

4
  • 2
    That is not a C program, neither is it C++. Possibly Objective-C. Commented Feb 4, 2015 at 13:08
  • 1
    Your title mentions NSStringWithFormat, which is Objective-C, but your code or question body don't even seem relevant to the title. Commented Feb 4, 2015 at 13:09
  • 1
    Oh, and a[i] = input; will make each array element point to the same char input[100]; which also goes out of scope outside the for loop. Commented Feb 4, 2015 at 13:12
  • Sorry for the wrong title. That was an old browser cache error. Commented Feb 4, 2015 at 13:15

1 Answer 1

3

If that was a C program, you would have undefined behavior because you have an array of pointers, and each pointer you make point to a variable inside a nested scope, which means that variable will be out of scope outside of the loop, and the pointers (who are all pointing to the same memory) will be stray leading to said undefined behavior.

Sign up to request clarification or add additional context in comments.

1 Comment

I would guess that it would be undefined behavior in Objective-C as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.